同时从另一个表中选择数据和计数

时间:2013-04-24 01:47:00

标签: mysql

我只是想回应文章并按用户评论的最多数量来订购。这是我的两张桌子

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            |

由于

2 个答案:

答案 0 :(得分: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 :(得分: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来保留所有文章,即使他们没有评论。

相关问题