SQL 仅选择存在多个关系的行

SQL Select only rows where multiple relationships exist(SQL 仅选择存在多个关系的行)
本文介绍了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_idprop_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 仅选择存在多个关系的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)