首页 > 解决方案 > 两列上的 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

非常感谢您的帮助:-)

标签: mysqlsql

解决方案


您可以使用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

推荐阅读