SQL Select only rows where multiple relationships exist(SQL 仅选择存在多个关系的行)
问题描述
给定一个父表'父'
╔═══════════╦══════════╗
║ 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 仅选择存在多个关系的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL 仅选择存在多个关系的行
基础教程推荐
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 无法解决整理冲突 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
