使用Rails中的联接表进行SQL Join [英] SQL Join using a join table from rails

查看:62
本文介绍了使用Rails中的联接表进行SQL Join的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我不确定对这些表进行联接的最佳方法是什么.我想使用一个JOIN,因为我相信它比将所有三个表都放在FROM上要快.所以,如果我有三个桌子...

So, I am not sure what the best way to do a join for these tables was. I want to use a JOIN because I believe it is faster than bring all three of the tables in on FROM. So, if i have three tables...

Table1
--id
--data

Table2
--id
--data

Table1_Table2
--table1_id
--table2_id

如何使用联接表对此数据​​进行联接?

How can I do a join for this data using the join table?

推荐答案

提及FROM子句中的所有表也是一种联接(隐式联接).不建议使用它,因为它可能导致所涉及表的笛卡尔积,以防您忘记在WHERE子句中添加谓词.

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.

Wikipedia JOIN文章和此关于join的非常不错的博客帖子阿特伍德.

我认为您对表之间的INNER JOIN感兴趣,尽管还存在其他变体.试试这个:

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
  INNER JOIN Table1_Table2 tt ON t1.id = tt.table1_id
  INNER JOIN Table2 t2 ON t2.id = tt.table2_id;

由于没有什么特别之处,我从选择列表中跳过了Table1_Table2列.

I skipped Table1_Table2 columns from the select list, as there's nothing special there.

这篇关于使用Rails中的联接表进行SQL Join的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆