簡體   English   中英

如何在LEFT JOIN中約束右手桌?

[英]How to constrain right hand table in LEFT JOIN?

我有兩個表:帖子和評論。 一篇文章有​​很多評論。

我經常想檢索所有帖子以及它們可能有的任何評論。 我通過左連接執行此操作,如下所示:

select p.post_id, p.content_status, p.post_title, c.comment_id, 
       c.content_status as comment_status 
from post p 
left join comment c on p.post_id = c.post

現在,我要排除狀態為“已批准”的所有帖子或評論。 我可以限制發布表沒有問題,並且仍然返回沒有評論的發布。 但是,一旦我限制了評論表,我就不再檢索沒有評論的帖子。

這是令人討厭的查詢:

select p.post_id, p.content_status, p.post_title, c.comment_id, 
       c.content_status as comment_status 
from post p  
left join comment c on p.post_id = c.post 
where p.content_status = 'Approved' and c.content_status = 'Approved'

只需將右側表上的條件移到ON子句中即可。

WHERE子句中的任何條件都將完全刪除行,而ON子句中的條件-根據需要-不會刪除行,而只是阻止匹配。

SELECT p.post_id, p.content_status, p.post_title, c.comment_id, 
       c.content_status AS comment_status 
FROM post p  
LEFT JOIN comment c 
  ON p.post_id = c.post AND c.content_status = 'Approved'
WHERE p.content_status = 'Approved'

SQLfiddle,由@ hims056提供

將左聯接表上的條件移到聯接條件中:

select p.post_id, p.content_status, p.post_title, c.comment_id, c.content_status as comment_status
from post p
left join comment c
  on p.post_id = c.post
  and c.content_status = 'Approved'
where p.content_status = 'Approved'

似乎鮮為人知的事實是,JOIN的ON子句可能包含與鍵無關的條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM