SQL 选择一个只有 child 的父级

标签 sql tags parent subset

如果你有父表

create table parent (
  pid int not null,
  name varchar(255)
)

和一个父子连接表
create table parent_child (
  pid int not null,
  cid int not null,
  foreign key (pid) references parent(pid),
  foreign key (cid) references child(cid)
)
create table child(
  cid int not null,
  name varchar(255)
)

我怎样才能找到所有 child 在以下列表中都有名字的所有 parent 的名字('dave'、'henry'、'myriam'、'jill')。

如果他们有一个不同名字的 child ,我不想看到 parent ,但如果他们有 1 个或多个 child ,并且他们所有的 child 在列表中都有名字,我想看到 parent 的名字。

我确实找到了这个 https://stackoverflow.com/a/304314/1916621这将帮助我找到一个有这些名字的 child 的 parent ,但我不知道如何找到那些只有在该列表子集中有名字的 child 的 parent 。

如果有人知道不同方法的性能权衡,则额外加分。

最佳答案

SELECT 
    p.pid, 
    p.name
FROM 
    parent p
WHERE NOT EXISTS (
    SELECT *
    FROM 
        parent_child pc 
        JOIN child c 
            ON pc.cid = c.cid
            AND c.name NOT IN ('dave','henry','myriam','jill')
    WHERE 
        p.pid = pc.pid
) AND EXISTS (
    SELECT *
    FROM 
        parent_child pc 
        JOIN child c 
            ON pc.cid = c.cid
            AND c.name IN ('dave','henry','myriam','jill')
    WHERE 
        p.pid = pc.pid
)

另一种方法...没有子查询,但附加 DISTINCT需要消除 parent 的重复从加入到 parent_child 的记录 table 。
SELECT DISTINCT
    p.pid, 
    p.name
FROM 
    parent p 
    JOIN parent_child pc_exists ON pc_exists.pid = p.pid
    JOIN child c_exists 
        ON c_exists.cid = pc_exists.cid
        AND c_exists.name IN ('dave','henry','myriam','jill')
    LEFT JOIN parent_child pc_notExists ON pc_notExists.pid = p.pid
    LEFT JOIN child c_notExists 
        ON c_notExists.cid = pc_notExists.cid
        AND c_notExists.name NOT IN ('dave','henry','myriam','jill')
WHERE
    c_notExists.cid IS NULL

关于SQL 选择一个只有 child 的父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13961438/

相关文章:

c# - 有没有办法将数据库记录视为对象

javascript - 解析 Javascript 中的特定 HTML 标签

javascript - PHP 相当于 JavaScript 的parentNode 属性

html - jsoup:如何选择具有满足条件的子节点的父节点

mysql - 如何从 1 更新 id 集?

mysql - 请教我如何优化这个 MySQL 查询

sql - BigQuery GROUP_CONCAT 和 ORDER BY

python - 从项目中 Grep 类/函数

python - 用于读取标签 Python 的正则表达式

iframe - 在 iframe 中单击子页面时,如何将父页面滚动到顶部?