2013-04-24 129 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

相关问题