我有两张表posts
和authors
。作者有很多帖子,所以有一个外键posts.author_id
。帖子还有一个approved_at
列datetime
,在帖子获得批准之前为NULL
那么如何选择所有没有批准的帖子的作者?
我可以选择至少一个批准的帖子的所有作者,如下所示:
SELECT * FROM authors
WHERE id IN
(
SELECT a.id FROM authors a
JOIN posts p ON a.id = p.author_id
AND p.approved_at IS NOT NULL
)
但我无法弄清楚如何做相反的事情:我想选择所有作者,其中所有的相关帖子都有approved_at = NULL
。我该如何选择?
答案 0 :(得分:2)
如果您想选择根本没有帖子或所有帖子未获批准的作者(或者如您所说 - 具有无已批准帖子的作者),请使用not exists
对我来说,这是最可读的方式:
select a.*
from authors as a
where
not exists
(
select *
from posts as p
where p.author_id = a.id and p.approved_at is not null
)
答案 1 :(得分:0)
如果postgres支持此语法,请尝试此方法
SELECT * FROM authors
WHERE id IN
(
SELECT a.id FROM authors a
JOIN posts p ON a.id = p.author_id
AND p.approved_at is NULL
except
SELECT a.id FROM authors a
JOIN posts p ON a.id = p.author_id
AND p.approved_at IS NOT NULL
)