在 SQL 中选择包含所有子项的父记录 [英] Select Parent Record With All Children in SQL
本文介绍了在 SQL 中选择包含所有子项的父记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两个表,父"和子".父子关系是多对多关系,通过标准的交叉引用表实现.
Let's say I have two tables, "Parent" and "Child". Parent-to-Child is a many:many relationship, implemented through a standard cross-referencing table.
我想使用 SQL(特别是 MS SQL Server 的 T-SQL;2005 语法是可以接受的)查找给定子集的所有成员引用的所有 Parent 记录.
I want to find all records of Parent that are referenced by ALL members of a given set of Child using SQL (in particular MS SQL Server's T-SQL; 2005 syntax is acceptable).
例如,假设我有:
- 列表项
- 父母爱丽丝
- 父母鲍勃
- 孩子查理引用了爱丽丝、鲍勃
- 孩子大卫引用了爱丽丝
- Child Eve 引用了 Bob
我的目标是:
- 如果我有孩子查理,我希望结果集包括爱丽丝和鲍勃
- 如果我有孩子查理和大卫,我希望结果集包括爱丽丝和不鲍勃.
- 如果我有孩子查理、大卫和夏娃,我希望结果集不包含任何人.
推荐答案
依靠一个数字技巧(其中父子链接的数量 = 子节点的数量,该父节点链接到所有子节点):
Relying on a numerical trick (where the number of parent-child links = the number of children, that parent is linked to all children):
SELECT Parent.ParentID, COUNT(*)
FROM Parent
INNER JOIN ChildParent
ON ChildParent.ParentID = Parent.ParentID
INNER JOIN Child
ON ChildParent.ChildID = Child.ChildID
WHERE <ChildFilterCriteria>
GROUP BY Parent.ParentID
HAVING COUNT(*) = (
SELECT COUNT(Child.ChildID)
FROM Child WHERE <ChildFilterCriteria>
)
这篇关于在 SQL 中选择包含所有子项的父记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文