Select所有子记录满足条件才记录父记录

Select only parent records when all children records meet conditions

我有两个表 A 和 B,当所有子项(在 Table B 中)满足条件时,我只需要父 A 的行。如果 B 中的一行不符合条件,那么我不需要父 A 的行。我想我需要在这里使用 exists,但不显示如何使用。

以下是数据表:

Table一个

Primary Key Level
1   low
2   low
3   high 
4   high 
5   low

Table乙

Primary Key Phase   Parent Primary Key
1   open    1
2   open    1
3   close   1
4   close   2
5   close   2
6   close   3
7   open    4
8   open    4
9   open    5
10  close   5

我正在尝试的查询:

select * 
from table_a, table_b
where table_a.level = 'low' and
      table_b.phase = 'close' and
      table_a.primary_key=table_b.parent_primary_key

但我的查询也会 return 行,其中 table_a.primary_key = 5。

基本上,我想要 returned 的唯一行是当 table_A.primary_key = 2 时,因为级别较低,并且两个子行的相位都等于关闭。

谢谢!

这是你想要的吗

select a.*
from table_a a
where a.level = 'low' and
      not exists (select 1
                  from table_b b
                  where b.parent_primary_key = a.primary_key and
                        b.phase <> 'close'
                 );

not exists 是双重否定。它检查没有 children 的相位不是 'close' —— 这基本上等同于说所有 children 都是 'close'。 (如果允许 NULL 个值,则逻辑不完全等价。)

或者:

select a.*
from table_a a
where a.level = 'low' and
      'close' = all (select phase
                  from table_b b
                  where b.parent_primary_key = a.primary_key
                 );