小编典典

Rails中的多个表联接

mysql

我如何将下面的MySQL查询写入Rails ActiveRecord

select
    A.*,
    B.* 
from
    raga_contest_applicants_songs AS A 
    join
        raga_contest_applicants AS B 
        ON B.contest_applicant_id = A.contest_applicant_id 
    join
        raga_contest_rounds AS C 
        ON C.contest_cat_id = B.contest_cat_id 
WHERE
    C.contest_cat_id = contest_cat_id 
GROUP BY
    C.contest_cat_id

我知道如何在两个表上编写联接;但是,我对如何在3个表上使用联接不是很有信心。


阅读 320

收藏
2020-05-17

共1个答案

小编典典

要重写您在问题中遇到的SQL查询,我认为它应该类似于以下内容(尽管我很难完全可视化您的模型关系,所以这有点猜测):

RagaContextApplicantsSong.
  joins(:raga_contest_applicants => [:raga_content_rounds], :contest_cat).
  group('raga_contest_rounds.contest_cat_id')

…这样该joins方法可以同时处理两个联接以及WHERE子句,最后是group调用。

作为更多参考:

如果要将多个关联加入同一模型,则可以简单地列出它们

Post.joins(:category, :comments)
Returns all posts that have a category and at least one comment

如果要加入嵌套表,则可以将它们列出为哈希表:

Post.joins(:comments => :guest)
Returns all comments made by a guest

嵌套关联,多个级别:

Category.joins(:posts => [{:comments => :guest}, :tags])
Returns all posts with their comments where the post has at least one comment made by a guest

您还可以链接ActiveRecord查询接口调用,例如:

Post.joins(:category, :comments)
...produces the same SQL as...
Post.joins(:category).joins(:comments)

如果所有其他方法均失败,则始终可以将SQL片段直接传递到joins方法中,以此作为从工作查询到达以ARQI为中心的内容的垫脚石

   Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
=> SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
2020-05-17