sql - 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 个标签的情况。
解决方案
这是一个关系划分问题,您希望商店具有所有可能的标签。这是一种使用聚合的方法:
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)
推荐阅读
- java - 与 MySQL 的连接密钥斗篷
- flutter - Flutter - 如何在 custompainter 中缩放和绘制图像?
- amazon-web-services - 托管在服务器上时如何为 Elasticsearch 配置 yml 文件?
- continuous-integration - 如何优雅地终止在 GitLab CI 中以“npm start”开头的监听 npm 应用程序?
- mongodb - 尝试配置 AWS Documentdb 但它返回超时
- java - 基于链表数组的实现 - 打印方法未编译
- crystal-reports - Crystal Report 的报表查看器“此处应有声明”
- python - 用第二个数组的两个值替换数组的数据
- python - 将字符偏移量转换为字偏移量的最简单方法
- flutter - Flutter 1.22.0 IOS 应用连接丢失问题