【问题标题】:MySQL: Best way finding rows, where associated list match a given listMySQL:查找行的最佳方法,其中关联列表与给定列表匹配
【发布时间】:2019-10-21 14:14:55
【问题描述】:

我建立了一个 SQL 语句,在这里解释:

我有一张这样的桌子Account

|-- Account ---|
| ID | comment |
| 1  | blabla1 |
| 2  | blabla2 |
| 3  | blabla3 |

我有一张桌子Customer 是这样的:

|---- Customer ----|
|   ID   | comment | 
| 111111 | blabla1 |
| 222222 | blabla2 |
| 333333 | blabla3 |

我有这样的关系Customer_To_Account

|----- Customer_To_Account -----|
| ID | account_id | customer_id |
| 1  |     1      |   111111    |
| 2  |     1      |   222222    |
| 3  |     1      |   333333    |
| 4  |     2      |   111111    |
| 5  |     2      |   222222    |
| 6  |     3      |   111111    |

我想在给定的列表(例如(111111、222222)中查找分配给客户的所有帐户。返回的帐户必须至少包含一个给定客户,并且不得包含不在给定列表中的客户。

预期结果:

  • 对于列表 (111111),结果只能是账户 3,因为账户 3 包含客户 111111 并且不包含任何其他客户。 账户 1 和 2 例如包含不在其中的客户 222222 列表 (111111) -> 所以不在结果中。

  • 对于列表 (111111, 222222),结果必须是帐户 2 和 3,因为它们 至少包含一个给定客户(111111、222222)和 不包含任何其他客户。帐户 1 包含客户 333333,不在列表中 (111111, 222222) -> 所以不在 结果。

我的查询:

    SELECT * FROM Account WHERE ID IN (
        SELECT distinct account_id FROM Customer_To_Account 
        WHERE customer_id IN("111111", "222222")) -- all accounts, that have one of these customers assigned
      AND ID NOT IN (
        SELECT distinct account_id FROM Customer_To_Account 
        WHERE customer_id NOT IN("111111", "222222")) -- all accounts, that have other customers assigned than the given customers

这会返回正确的结果,但查询的性能并不是很差,因为它选择了所有帐户的 ID,至少有一个客户,但不在给定列表中。

对于这样的用例,是否有人有更好的想法/查询?

非常感谢!

海维尔

【问题讨论】:

    标签: mysql sql associations


    【解决方案1】:

    使用聚合怎么样?

    select account_id
    from customer_to_account ca
    group by account_id
    having sum( customer_id in ( . . . ) ) > 0 and  -- at least 1
           sum( customer_id not in ( . . . ) ) = 0  -- no others
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-28
      • 2014-02-24
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 2019-04-16
      • 2021-09-29
      相关资源
      最近更新 更多