轨道中的多个表连接

时间:2013-04-21 12:40:49

标签: mysql ruby-on-rails activerecord

如何将下面的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个表上使用连接不太自信。

1 个答案:

答案 0 :(得分:62)

要重写你在问题中得到的SQL查询,我认为它应该如下(虽然我很难完全可视化你的模型关系,所以这有点猜测):

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

...这样joins方法会处理两个连接以及WHERE子句,最后是group调用。

更多供参考:

如果您要将多个关联加入同一模型you can simply list them

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)

如果所有其他方法都失败了,你可以随时pass a SQL fragment directly into the joins method作为从工作查询到更多以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