一個帖子可以有意見或沒有。使用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.text
或comment.text
或reply.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代表帖子,評論,回覆。
嘗試使用'和'而不是''&& – 2011-06-04 22:34:56
如果'刪除= 0'意味着刪除評論,那麼這將顯示所有刪除帖子 - 刪除評論組合。 – 2011-06-04 22:36:38
返回0,這不是結果。 編輯:我怎麼能讓它做我想要的? – fxuser 2011-06-04 22:37:11