2010-06-02 55 views
1

我有多個表如何獲得在左另一個表的計數加入

post 
    id Name 
    1 post-name1 
    2 post-name2 

user 
    id username 
    1 user1 
    2 user2 

post_user 
    post_id user_id 
    1   1 
    2   1 

post_comments 
    post_id comment_id 
    1   1 
    1   2 
    1   3 

我使用的是這樣的查詢:

SELECT post.id, post.title, user.id AS uid, username 
FROM `post` 
LEFT JOIN post_user ON post.id = post_user.post_id 
LEFT JOIN user ON user.id = post_user.user_id 
ORDER BY post_date DESC 

它按預期工作。不過,我希望獲得每篇文章的評論數量。那麼,我該如何修改這個查詢,以便我可以得到評論的數量。

任何想法?

回答

11
SELECT post.id, post.title, user.id AS uid, username, COALESCE(x.cnt,0) AS comment_count 
FROM `post` 
LEFT JOIN post_user ON post.id = post_user.post_id 
LEFT JOIN user ON user.id = post_user.user_id 
LEFT OUTER JOIN (SELECT post_id, count(*) cnt FROM post_comments GROUP BY post_id) x ON post.id = x.post_id 
ORDER BY post_date DESC 

編輯:使其成爲一個外連接的情況下有沒有任何意見

EDIT2:改變ISNULL凝聚

+0

請確保您說明帖子的評論爲零的情況。在您的選擇列表中,使用 ,ISNULL(x.cnt,0)AS comment_count – cortijon 2010-06-02 16:46:36

+0

@MrGumbe - 好點,謝謝。我考慮過這個問題,但不確定他使用的是哪個數據庫,因爲ISNULL不適用於某些數據庫(即使用Oracle,您必須使用NVL)。 – dcp 2010-06-02 16:50:31

+0

沒有ISNULL功能。 MySQL說#1582 - 調用本地函數'ISNULL'時的參數數不正確 – Sinan 2010-06-02 16:59:43

1

這個編輯版本顯示沒有評論行:

SELECT post.id, post.title, user.id AS uid, username, count(post_comments.comment_id) as comment_count 
FROM `post` 
LEFT JOIN post_user ON post.id = post_user.post_id 
LEFT JOIN user ON user.id = post_user.user_id 
LEFT JOIN post_comments ON post_comments.post_id = post.id 
GROUP BY post.id 
ORDER BY post_date DESC 

例如:

+----+------------+------+----------+---------------+ 
| id | title  | uid | username | comment_count | 
+----+------------+------+----------+---------------+ 
| 3 | post-name3 | 2 | user2 |    0 | 
| 1 | post-name1 | 1 | user1 |    3 | 
| 2 | post-name2 | 1 | user1 |    1 | 
+----+------------+------+----------+---------------+ 
3 rows in set (0.01 sec) 
+0

這不顯示0個零評論的行。任何想法? – Sinan 2010-06-02 16:58:13

+0

@Sinan - 看到我的答案,它處理這種情況。 – dcp 2010-06-02 17:06:26

相關問題