简体   繁体   English

Postgres加入Rails查询

[英]Postgres Join Query on Rails

I have researched a lot and I can't find the answer for my question. 我进行了很多研究,但找不到我的问题的答案。 I have the following setup on my Rails app: 我在Rails应用程序上进行了以下设置:

class Group < ActiveRecord::Base
  has_many :people
  # ...
end

class City < ActiveRecord::Base
  has_many :people
  # ...
end

class Person < ActiveRecord::Base
  belongs_to :city
  belongs_to :group
  # ...
end

The people have the column :role that is 0 or 1 . 人们的列:role01

I want to get all the groups that have at least one person with role == 0 and one person with the role == 1 . 我想获得所有至少具有一个role == 0人和一个role == 1

Any idea? 任何想法? I'm using Postgres by the way. 我正在使用Postgres。

Here's a query I just tested on my SQLite3 database (should work on Postgres too I believe): 这是我刚刚在SQLite3数据库上测试过的查询(我相信也应该在Postgres上工作):

 Group.select("groups.*").joins("LEFT JOIN people on groups.id = people.group_id").where("people.role==0 OR people.role==1").group("id")

Here I assume you've already added the foreign key group_id in your people migration. 在这里,我假设您已经在人员迁移中添加了外键group_id。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM