我有两个表 A 和 B,当所有子项(在表 B 中)都满足条件时,我只需要父 A 的行。如果 B 中的一行不符合条件,那么我不需要父 A 的行。我想我需要在这里使用 exists,但不显示如何使用。
数据表如下:
表A
Primary Key Level
1 low
2 low
3 high
4 high
5 low
表B
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
但我的查询也会返回 table_a.primary_key = 5 的行。
基本上,我想要返回的唯一行是 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'
);
不存在
是双重否定。它检查是否没有子级处于 'close'
之外的阶段——这基本上等同于说所有子级都是 'close'
。 (如果允许使用 NULL
值,则逻辑不完全相同。)
关于sql - 当所有子记录满足条件时只选择父记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42439273/