mysql - 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)等给定列表中查找分配给客户的所有帐户。返回的帐户必须至少包含一个给定的客户,并且它们不得包含不在给定列表中的客户。
预期结果:
对于列表 (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,这些 ID 至少有一个客户,但不在给定的列表中。
有人对这样的用例有更好的想法/查询吗?
非常感谢!
海维尔
解决方案
如何使用聚合?
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
推荐阅读
- c# - 从 CSV 数据文件中以 c# 绘制的图表中的峰值检测(查找两个峰值之间的距离)
- python - Django 表单需要重新提交
- xcode - xcode 11 更新后 Xamarin.iOS 项目未运行
- wpf - 在 WPF 应用程序中获取 Autofac 最内部范围
- javascript - 如何动态传递道具?
- c# - 从 LiteDB 执行 LINQ 时转换为 .ToList() 时的性能问题大约。100 万条记录
- sql - 加入前与加入后选择列
- angular - Angular中的渐进式上传文件
- python - 如何在开发过程中重命名 Flask WSGI App?
- laravel - 如何在 Laravel eloquent 中使用 via 对象获取数据?