Skip to content

Instantly share code, notes, and snippets.

@solnic
Created October 11, 2012 16:16
Show Gist options
  • Select an option

  • Save solnic/3873534 to your computer and use it in GitHub Desktop.

Select an option

Save solnic/3873534 to your computer and use it in GitHub Desktop.
SELECT DISTINCT "song_id", "name", "tag_name"
FROM (
SELECT * FROM (
SELECT "id" AS "song_id", "name" FROM "songs"
) AS "left" NATURAL JOIN (
SELECT * FROM "song_tags" AS "left"
NATURAL JOIN (
SELECT "id" AS "tag_id", "name" AS "tag_name" FROM "tags"
) AS "right"
) AS "right"
) AS "songs_song_tags_tags"
tags = Relation::Base.new :tags, [ [ :id, Integer ], [ :name, String ] ]
songs = Relation::Base.new :songs, [ [ :id, Integer ], [ :name, String ] ]
song_tags = Relation::Base.new :song_tags, [ [ :song_id, Integer ], [ :tag_id, Integer ] ]
SQL::Generator::Relation.visit(
songs.rename(:id => :song_id).join(song_tags.join(tags.rename(:id => :tag_id, :name => :tag_name))).project([ :song_id, :name, :tag_name ])
).to_s
@solnic
Copy link
Copy Markdown
Author

solnic commented Oct 13, 2012

@dkubb yeah all those crazy queries are totally correct :) Good thing is that in many cases running a single query to eagerly load associated objects should be faster than running multiple separate queries for all the associations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment