mysql - 两列上的 SQL 查询过滤器

标签 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 和 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

关于mysql - 两列上的 SQL 查询过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58100692/

相关文章:

mysql - AWS RDS 性能洞察 - 查看完整查询

sql - 括号对mysql结果有影响吗?

MySQL按列和列值排序

mysql - WHERE NOT EXIST 附近的语法错误

mysql - 连接查询中的默认空值

mysql - 将新列添加到现有表并将其显示到 View Blade 中(LARAVEL,mysql)

MySQL查询,其中一列行的结果与下一列相加

sql - Postgresql:子查询的替代方法可以使查询更高效?

sql - 如何仅检索自上次 SQL 查询以来更新/新的记录?

SQL Server 整数与十进制 SUM