1

我有(我认为)SQL 非常简单的问题。我有两个表:Posts(id, body, user_id) 和 Reports(id, user_id, post_id)。

我想显示给定用户的所有帖子,他没有将其标记为已报告。

我建立这样的查询:

Select * FROM posts LEFT OUTER JOIN 
reports ON reports.post_id = posts.id WHERE reports.id IS NULL

但是,它需要所有报告,而不仅仅是我的用户添加的报告。当然添加Where reports.id IS NULL AND reports.user_id = 123是行不通的……有什么解决方案,或者我应该做子查询吗?

顺便说一句:我认为这不会产生任何影响,但我正在运行 postgres 9.x

提前感谢您的帮助!

4

1 回答 1

3

添加reports.user_id = 123连接条件,而不是 where 子句。这将仅加入reports具有user_id = 123并仅消除那些匹配的行:

SELECT *
FROM posts
LEFT OUTER JOIN reports ON reports.post_id = posts.id
    AND reports.user_id = 123
WHERE reports.id IS NULL

或者,使用WHERE NOT EXISTS

SELECT *
FROM posts
WHERE NOT EXISTS
(
    SELECT 1
    FROM reports 
    WHERE reports.post_id = posts.id
    AND reports.user_id = 123
)
于 2013-03-14T09:01:05.757 回答