问题描述
给定一个父表'父'
╔═══════════╦══════════╗
║ PARENT_ID ║ NAME ║
╠═══════════╬══════════╣
║ 1 ║ bob ║
║ 2 ║ carol ║
║ 3 ║ stew ║
╚═══════════╩══════════╝
以及父级和(此处未指定)属性表之间的多对多关系表rel"
and a many-many relationship table 'rel' between parent and a (here unspecified) property table
╔═══════════╦═══════════╗
║ PARENT_ID ║ PROP_ID ║
╠═══════════╬═══════════╣
║ 1 ║ 5 ║
║ 1 ║ 1 ║
║ 2 ║ 5 ║
║ 2 ║ 4 ║
║ 2 ║ 1 ║
║ 3 ║ 1 ║
║ 3 ║ 3 ║
╚═══════════╩═══════════╝
如何选择具有所有一组指定关系的所有父级?例如.使用示例数据,如何找到同时拥有属性 5 和属性 1 的所有父母?
How can I select all parents that have all of a specified set of relationships? E.g. with the sample data, how can I find all parents that have both property 5 and 1?
同样的问题,但要求 完全 匹配:SQL 仅选择存在精确多重关系的行
edit: Same question but with requirement for an exact match: SQL Select only rows where exact multiple relationships exist
推荐答案
这叫做 关系划分
This is called Relational Division
SELECT a.name
FROM parent a
INNER JOIN rel b
ON a.parent_ID = b.parent_ID
WHERE b.prop_id IN (1,5)
GROUP BY a.name
HAVING COUNT(*) = 2
- SQLFiddle 演示链接
更新 1
如果没有对每个 parent_id 的 prop_id 强制实施 唯一约束,则在这种情况下需要 DISTINCT.
if unique constraint was not enforce on prop_id for every parent_id, DISTINCT is needed on this case.
SELECT a.name
FROM parent a
INNER JOIN rel b
ON a.parent_ID = b.parent_ID
WHERE b.prop_id IN (1,5)
GROUP BY a.name
HAVING COUNT(DISTINCT b.prop_id) = 2
这篇关于SQL 仅选择存在多个关系的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)