SQL 选择所有相关条目都满足条件的地方

时间:2021-03-22 21:45:10

标签: sql join heroku-postgres

表A:

id | name | type 

表 B:

id | a_id | structure

其中 A 有许多 B。

我想查询所有 As 表 B 中没有相关条目的结构 = 'successful'

我正在尝试做

select a.name
from a
inner join b on a.id = b.a_id where a.type = 'note' and a.id = ALL (Select a_id from B where structure <> 'successful')

但我得到 0 个结果。 (Heroku 数据剪辑)

样本数据

id | name | type
01 | woof | note
02 | meow | note
03 | who  | free

id | a_id | structure
01 | 01 | open
02 | 01 | draft
03 | 02 | draft
04 | 02 | successful
05 | 02 | open
06 | 03 | open

运行此查询应返回

woof

因为我希望 A 中的所有实体都具有关联的注释类型,但表 B 中的所有相关条目都没有结构 = 'successful'

1 个答案:

答案 0 :(得分:1)

一个简单的 not exists 会满足您的标准吗?

select a.name
from TableA a
where a.type='note'
and not exists (select * from TableB b where b.a_id=a.id and b.structure='successful')

结果:'woof'

相关问题