问题描述
我的桌子是这样设置的:
I have tables set up like so:
Parent
------
id, ...
Child
-----
id, parent_id, x, y
如果包含给定 parent_id 的 Child 中的所有行满足涉及 x 和 y 的条件(在我的情况下为 x = y).
I want to find the Parents, or the distinct parent_id(s), if all of the rows in Child containing a given parent_id meet a criteria involving x and y(in my case x = y).
例如:
Parent
------
id
1
2
3
Child
id, parent_id, x, y
1, 1, 2, 3
2, 1, 3, 4
3, 2, 5, 5
4, 2, 6, 7
5, 3, 8, 8
6, 3, 9, 9
将导致 3.目前,我有一个查询,可以找到 any 子项满足条件的 parent_ids.然后我使用它来检索这些记录并在代码中检查它们是否所有孩子都符合条件.使用示例数据,我获得 parent_id 2 和 3,获得所有孩子的两个父记录,并进行评估.如果可能,我想通过单个查询来完成此操作.
would result in 3. Currently, I have a query that finds parent_ids that any of the children meet the criteria. I then use that to retrieve those records and check them in code if all the children meet the criteria. With the example data, I get parent_id 2 and 3, get the two parent records with all children, and evaluate. I want to do this with a single query, if possible.
推荐答案
您可以使用 NOT EXISTS
SELECT id
FROM Parent p
WHERE NOT EXISTS
(
SELECT 1 FROM Child c
WHERE c.parent_Id = p.id
AND c.x <> c.y
)
这是 sql-fiddle:http://sqlfiddle.com/#!3/20128/1/0
Here's the sql-fiddle: http://sqlfiddle.com/#!3/20128/1/0
这篇关于如果所有孩子都符合条件,则选择父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!