【问题标题】:Finding all the data for which no associated data present without subquery在没有子查询的情况下查找不存在关联数据的所有数据
【发布时间】:2017-09-05 07:14:13
【问题描述】:

我有两张桌子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.id 最终将为零

标签: ruby-on-rails ruby ruby-on-rails-4 postgresql-9.1


【解决方案1】:
User.eager_load(:contacts).where(contacts: {id: nil, category_id: 1 }) 

eager_load 对 'contacts' 表执行左外连接。对于所有未与联系人表关联的用户 - 在此查询中,contacts.id 最终将为 nil

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 2011-08-31
    相关资源
    最近更新 更多