SQL Query根据子记录的多个条件获取父记录

时间:2014-05-30 08:51:02

标签: sql database oracle

我有两个表Parent P和Child C

Id Name
1   AAA
2   BBB
3   CCC

儿童

Id ParId Name Value
11 1     XXX    1
12 1     YYY    7
19 1     ZZZ    9
13 2     XXX    1
14 2     YYY    2
20 1     ZZZ    7
15 3     XXX    1
16 3     YYY    2
18 3     ZZZ    8

我想获取XXX值为1且YYY不为2或zzz值不为7的父记录。 在这种情况下,我应该得到1和3作为结果。请建议。

3 个答案:

答案 0 :(得分:0)

select distinct p.id 
from parent p 
join child c 
    on p.id=c.parid 
where (c.name='XXX' and c.value = 1) or (c.name='YYY' and c.value = 2) or ...

答案 1 :(得分:0)

select * from parent p where 
    not exists(select * from child c where p.id  = c.parid and (c.xxx = 1))
    and not exists(select * from child c where p.id  = c.parid and (c.yyy = 2))
    and not exists(select * from child c where p.id  = c.parid and (c.zzz = 7))

答案 2 :(得分:0)

可以使用HAVING语句在查询的CASE部分中检查规则。

如果必须检查所有名称,即如果孩子不具有所有三个名称,则不应该在结果集中,对三个规则的检查是静态的

SELECT c.ParId, p.Name
FROM   Child c
       INNER JOIN Parent p ON c.ParID = p.Id
GROUP BY c.ParId, p.Name
HAVING SUM(CASE WHEN c.Name = 'XXX' AND c.Value = 1 Then 1
                WHEN c.Name = 'YYY' AND c.Value <> 2 Then 1
                WHEN c.Name = 'ZZZ' AND c.Value <> 7 Then 1
                ELSE 0
           END) = 3;

如果只需要检查数据中的名称,即如果孩子只有'XXX'并且它的值是1那么它的父亲应该在结果集中,检查是动态的

SELECT c.ParId, p.Name
FROM   Child c
       INNER JOIN Parent p ON c.ParID = p.Id
WHERE  c.NAME IN ('XXX', 'YYY', 'ZZZ')
GROUP BY c.ParId, p.Name
HAVING SUM(CASE WHEN c.Name = 'XXX' AND c.Value = 1 Then 1
                WHEN c.Name = 'YYY' AND c.Value <> 2 Then 1
                WHEN c.Name = 'ZZZ' AND c.Value <> 7 Then 1
                ELSE 0
           END) = COUNT(DISTINCT c.NAME)