繁体   English   中英

左外连接条件

[英]LEFT Outer join with conditions

我有(我认为)SQL非常简单的问题。 我有两个表:帖子(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.

在此先感谢您的帮助!

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

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
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM