Select parent if all children meet criteria

荒凉一梦 提交于 2019-12-04 19:20:55

问题


I have tables set up like so:

Parent
------
id, ...

Child
-----
id, parent_id, 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).

For example:

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

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.


回答1:


You can use 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
)

Edit: Here's the sql-fiddle: http://sqlfiddle.com/#!3/20128/1/0




回答2:


This is what you need?

  select id from parent where id not in(
    select parent_id from chile 
    where x<>y
    group by parent_id)



回答3:


Should join 2 tables first because the parents does not have children that will satisfy

And should add index for pa_id column

SELECT DISTINCT pa.id 
FROM pa INNER JOIN c ON c.pa_id = pa.id 
WHERE NOT EXISTS ( SELECT 1 FROM c WHERE c.parent_Id = p.id and c.x <> c.y )


来源:https://stackoverflow.com/questions/12075068/select-parent-if-all-children-meet-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!