找到所有这些没有相关数据目前没有子查询
问题描述:
我有两个表users
& contacts
找到所有这些没有相关数据目前没有子查询
用户
| id | name | last_name |
|:-----------|------------:|:------------:|
| 1 | John | Abraham
| 2 | Tom | column
| 3 | Bob | Warner
| 4 | Smith | Warne
| 5 | Brad | Pitt
接触
| id | user_id | contact |active | category_id |
|:-----------|-----------:|:-------------:|:---------:|:------------:|
| 1 | 1 | 132423 | false | 2
| 2 | 1 | 131423 | true | 3
| 3 | 1 | 142423 | true | 1
| 4 | 2 | 132413 | true | 1
| 5 | 2 | 132425 | false | 2
| 6 | 2 | 131420 | true | 3
| 7 | 3 | 131323 | true | 3
| 8 | 3 | 332423 | true | 1
| 9 | 3 | 232423 | false | 2
| 10 | 4 | 132523 | false | 1
我想第1类用户谁拥有数据没有活动(false)
或没有该类别联系人的用户以及以下联系人
| id | name | last_name |
|:-----------|------------:|:------------:|
| 4 | Smith | Warne
| 5 | Brad | Pitt
我想是这样,但之后没有工作
User.includes(:contacts).where(contacts: {user_id: nil, category_id: 1 })
我可以使用两种不同的查询做到这一点,但没有得到如何把它写在一个单一的查询
u_ids = Conatct.where(category_id: 1, active: true).pluck(:user_id)
users = User.where.not(id: u_ids)
答
User.eager_load(:contacts).where(contacts: {id: nil, category_id: 1 })
eager_load在“contacts”表上执行左外连接。对于与联系人表格没有关联的所有用户 - contacts.id将最终为零,用于此查询
'User.eager_load(:contacts).where(contacts:{id:nil,category_id:1}) ' eager_load在'contacts'表上执行左外连接。对于没有与联系人表关联的所有用户,contacts.id将最终为零 – mgidea