首页 > 解决方案 > Postgres 中的记录交集

问题描述

假设我有多个与它们关联的商店的标签,如下所示:

label_id | store_id
--------------------
label_1  | store_1
label_1  | store_2
label_1  | store_3
label_2  | store_2
label_2  | store_3
label_3  | store_1
label_3  | store_2

SQL(或jooq)中是否有任何好的方法来获取标签交集处的所有商店ID?意思是只返回上面示例中的 store_2,因为 store_2 与 label_1、label_2 和 label_3 相关联?我想要一种通用方法来处理我有 n 个标签的情况。

标签: sqldatabasepostgresqljooqrelational-division

解决方案


这是一个关系划分问题,您希望商店具有所有可能的标签。这是一种使用聚合的方法:

select store_id
from mytable
group by store_id
having count(*) = (select count(distinct label_id) from mytable)

请注意,这假定没有重复的(store_id, label_id)元组。否则,您需要将having子句更改为:

having count(distinct label_id) = (select count(distinct label_id) from mytable)

推荐阅读