Sql Join Using A Join Table From Rails
Solution 1:
Mentioning all tables in the FROM clause is also a join, implicit one. It is not recommended to use it as it might lead to a Cartesian product of the tables involved in case you'll forget to add predicates in the WHERE clause.
Have a look on the Wikipedia JOIN article and also at this very nice blogpost about joins by Jeff Atwood.
I think that you're interested in the INNER JOIN between the tables, although other variants exists. Try this:
SELECT t1.*, t2.*FROM Table1 t1
INNERJOIN Table1_Table2 tt ON t1.id = tt.table1_id
INNERJOIN Table2 t2 ON t2.id = tt.table2_id;
I skipped Table1_Table2 columns from the select list, as there's nothing special there.
Solution 2:
While the above solution works, you might want to give the rails-way solution a try
Since you require a join table with only the primary keys of the participating tables, you can loop into has_and_belongs_to_many association. It does the same as the SQL query behind the scenes and is a neater solution. You can also look into has_many through association(also explained in the linked railscasts) if you want to add more columns to the join table.
Post a Comment for "Sql Join Using A Join Table From Rails"