2013-04-24 30 views
1

我只想回顯文章並按用戶評論的最多數量排序。這是我的兩個表同時從另一個表中選擇數據和計數

tbl_articles

article_id | articles_title | 
1   |  This is 1st | 
2   |  This 2nd | 

tbl_comment:

comment_id | user_id  | article_id | comment_msg 
1   |  1  | 1  | my comment1 
2   |  1  | 2  | my comment2 
3   |  2  | 1  | some comment1 

如何加入這些表,並迫使這樣的結果

article_id|articles_title| comment_count | 
    1  | This is 1st | 2   | 
    2  | This 2nd | 1   | 

感謝

+0

您是否還想按comment_count排序結果,即在結果列表中首先評論最多的文章? – 2013-04-24 15:56:36

回答

2

的下面的查詢使用INNER JOIN,只有至少1評論纔會顯示結果中的所有文章。如果您要顯示文章,甚至沒有評論,請將INNER JOIN更改爲LEFT JOIN

SELECT a.article_ID, 
     a.article_title, 
     COUNT(*) Comment_Count 
FROM articles a 
     INNER JOIN comment b 
      ON a.article_ID = b.article_ID 
GROUP BY a.article_ID, a.article_title 

爲了進一步獲得更多的知識有關加入,請訪問以下鏈接:

+1

工作正常,謝謝。我已經是新來的sql聯接,感謝您的鏈接 – 2013-04-24 01:58:55

+0

不客氣':D' – 2013-04-24 01:59:39

1

這是一個聚集一個簡單的連接查詢:

select article_id, articles_title, count(c.comment_id) as comment_count 
from tbl_articles a left outer join 
    tbl_comment c 
    on a.article_id = c.article_id 
group by article_id, articles_title 

這將使用left outer join保留所有的物品,即使他們沒有意見。

+0

thaks。我只是不知道在連接中添加計數部分的位置 – 2013-04-24 01:58:27

相關問題