2011-06-04 34 views
1

用下面的表PHP MySQL的左連接的where子句錯誤

帖子

  • ID
  • POST_ID
  • USER_ID

評論

  • ID
  • POST_ID
  • COMMENT_ID
  • user_id說明
  • 刪除

回覆

  • ID
  • POST_ID
  • reply_id
  • user_id說明
  • 刪除

我試圖讓每一個意見,並從每個post.post_id和post.user_id回覆= 'x' 和評論或回覆不會被刪除(0)

這就是我試圖

SELECT * 
FROM posts p 
LEFT JOIN comments c ON p.id=c.post_id 
LEFT JOIN replies r ON p.id=r.post_id 
WHERE p.user_id=$user_id 
&& c.deleted='0' && r.deleted='0' 

不工作...

+2

嘗試使用'和'而不是''&& – 2011-06-04 22:34:56

+0

如果'刪除= 0'意味着刪除評論,那麼這將顯示所有刪除帖子 - 刪除評論組合。 – 2011-06-04 22:36:38

+0

返回0,這不是結果。 編輯:我怎麼能讓它做我想要的? – fxuser 2011-06-04 22:37:11

回答

0

一個帖子可以有意見或沒有。使用LEFT JOIN而不是INNER JOIN

帖子可能有答覆或不答覆。在該連接中使用LEFT JOIN而不是INNER JOIN

當使用LEFT JOIN,像WHERE comments.deleted = 0的條件包括場(從左側右表(comments)JOIN),所述左連接被取消。所以,我們應該把這個條件放在ON條款中,而不是在WHERE中。

SELECT * 
FROM posts p 
    LEFT JOIN comments c 
    ON p.post_id = c.post_id 
    AND c.deleted = 0 
    LEFT JOIN replies r 
    ON p.post_id = r.post_id 
    AND r.deleted = 0 
WHERE p.user_id = $user_id 

思路更加清晰,上面會顯示這個問題介紹了什麼,但例說,4條評論和3篇回覆,12列將返回(3×4)。這可能不是想要的。以下第二次嘗試沒有這樣的問題。

我沒有在表格中看到post.textcomment.textreply.text,但無論如何,您都會明白。如果不合適,您可以刪除3 text行。

(SELECT p.post_id  AS post_id 
     , 0    AS type 
     , p.post_id  AS id 
     , p.text  AS text 
    FROM posts p 
    WHERE p.user_id = $user_id 
) 
UNION ALL 
    (SELECT p.post_id  AS post_id 
     , 1    AS type 
     , c.comment_id AS id 
     , c.text  AS text 
    FROM posts p 
     JOIN comments c 
     ON p.post_id = c.post_id 
    WHERE p.user_id = $user_id 
     AND c.deleted = 0 
) 
UNION ALL 
    (SELECT p.post_id  AS post_id 
     , 2    AS type 
     , r.reply_id AS id 
     , r.text  AS text 
    FROM posts p 
     JOIN replies r 
     ON p.post_id = r.post_id 
    WHERE p.user_id = $user_id 
     AND r.deleted = 0 
) 
ORDER BY post_id 
     , post_type 
     , id 

0,1,2代表帖子,評論,回覆。

+0

,我實際上使用LEFT。 – fxuser 2011-06-04 22:41:20

+0

我試過選擇查詢,但它仍然統計刪除的評論(有值1) – fxuser 2011-06-04 22:47:43

+0

@fxuser:你想評論評論和回覆嗎?或者展示他們? – 2011-06-04 22:57:16

1

您需要將刪除的檢查加入聯接子句。這應做到:

SELECT * 
FROM posts p 
LEFT JOIN comments c ON c.post_id = p.post_id AND NOT c.deleted 
LEFT JOIN replies r ON r.post_id = p.post_id AND NOT r.deleted 
WHERE p.user_id = $user_id 

注:不知道c.post_id加入到p.id或p.post_id - 按要求chenge on子句

+0

仍然計算刪除的評論或帖子..如果我刪除其中一個連接它會顯示正確的數據從評論或答覆,但他們都不工作... – fxuser 2011-06-04 22:58:11