mysql - 两列上的 SQL 查询过滤器
问题描述
我有一个包含这些列的表:
id | partner_id | product_id
-----------------------------
1 | 2 | 71
2 | 2 | 83
3 | 3 | 71
4 | 4 | 83
5 | 4 | 71
6 | 5 | 22
7 | 4 | 55
我只想要 partner_id 具有 product_id 83 AND 71 的行,如下所示:
id | partner_id | product_id
-----------------------------
1 | 2 | 71
2 | 2 | 83
4 | 4 | 83
5 | 4 | 71
非常感谢您的帮助:-)
解决方案
您可以使用exists
:
select t.*
from t
where t.product_id in (71, 83) and
exists (select 1
from t t2
where t2.partner_id = t.partner_id and
t2.product_id in (71, 83) and
t2.product_id <> t.product_id
);
但是,如果您只想要合作伙伴,这也可能有意义。在这种情况下,您可以使用group by
:
select partner_id
from t
where product_id in (71, 83)
group by partner_id
having count(*) = 2; -- assuming no duplicates
推荐阅读
- python - 从 Python 2 环境打开 Spyder 仍然在 Spyder 中运行 Python 3
- php - 如何创建和管理基于 Web 的 cron 作业
- python-3.x - 退出时打印日志文件中的所有 print()
- php - PHP更新数据库的问题
- ios - View Debug 中的 Collection View Frame 与代码不同
- java - 如何在firebase中比较来自不同UID的积分
- javascript - 如何为对象编写全局 get+set 方法
- javascript - 当使用流星在科尔多瓦应用程序中发生网络变化时在服务器之间动态切换
- javascript - WDS(Webpack 开发服务器)在 VUEJS 中断开连接
- gitlab - Gitlab中的用户分组