我有两个表 A 和 B,当所有子项(表 B 中)满足条件时,我只需要父项 A 的行。如果 B 中的一行不符合条件,那么我不需要父 A 的行。我想我需要在这里使用存在,但不展示如何使用。
以下是数据表:
Table 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 时,因为级别较低,并且两个子行都有一个等于 close 的阶段。
谢谢你!
这是你想要的吗
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'
);
The not exists
是双重否定。它检查是否没有其他阶段的孩子'close'
——这基本上等于说所有的孩子都是'close'
. (If NULL
值是允许的,逻辑并不完全等同。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)