首页 > 解决方案 > MySQL:查找行的最佳方法,其中关联列表与给定列表匹配

问题描述

我建立了一个 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)等给定列表中查找分配给客户的所有帐户。返回的帐户必须至少包含一个给定的客户,并且它们不得包含不在给定列表中的客户。

预期结果:

我的查询:

    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,这些 ID 至少有一个客户,但不在给定的列表中。

有人对这样的用例有更好的想法/查询吗?

非常感谢!

海维尔

标签: mysqlsqlassociations

解决方案


如何使用聚合?

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

推荐阅读