查询以查找A中所有记录,其中B中没有针对特定条件的连接记录

时间:2018-12-20 12:22:32

标签: sql postgresql

我试图构造一个查询来查找PostgreSQL表(a)中的所有记录,

  • b中根本没有 条记录,其中有state='ready'

在表b中没有记录的状态为state='ready'的原因没关系(可以是没有关联,关联为null,状态不同或状态为空)

在下面的示例中,我希望在表2,3,4中找到ID为a的记录。

我尝试了左联接,但无法使其正常工作。

PS。该查询必须高效,因为表具有数百万条记录。

https://www.db-fiddle.com/f/5thdgDkv5B6Mx56NyHfoiz/0

2 个答案:

答案 0 :(得分:0)

想必,您只想要not exists

select a.*
from a
where not exists (select 1
                  from b
                  where b.? = a.? and  -- whatever the join conditions are
                        b.state = 'ready'
                 );

答案 1 :(得分:0)

尝试一下:

SELECT * FROM a WHERE id NOT IN 
(SELECT b.a_id FROM b WHERE b.state = 'ready');

https://www.db-fiddle.com/f/5thdgDkv5B6Mx56NyHfoiz/2

相关问题