来自一个表列的MySQL连接/求和值与来自另一个表的列的计数值

时间:2014-04-18 18:10:43

标签: php mysql sql count sum

表1 - “新闻”

--------------------------------------
|news_id|news_title|fb_comments_count|
--------------------------------------
|     1|        XYZ|                0|
|     2|        ABC|               32|
|     3|        DEF|                5|
--------------------------------------

表2 - “news_comments”

------------------------------
|com_id|   news_id|   comment|
------------------------------
|     1|         1| blablabla|
|     2|         2| test     |
|     3|         1| comment  |
|     4|         1| asdf     |
------------------------------

我需要获得每条新闻的总评论总数,其中第一张表中的Facebook评论数和其他表中每条特定新闻的评论总数都计算在一起。

像这样 - “总评论”:

-----------------------------------
|   id | news_id  | total comments (fb_comments + count of comments from comments table)
-----------------------------------
|     1|        2 |             33|
|     2|        3 |              5|
|     3|        1 |              3|
-----------------------------------

提前致谢! :)

2 个答案:

答案 0 :(得分:0)

简单加入和分组依据可以使用COUNT()计算所有评论。然后只需将其添加到fb_comment_count即可。我们使用LEFT JOIN来确保它还包含news_comments中没有出现的news_id,并且仅将COUNT()应用于c.com_id,以确保在没有news_comments时这将为这些情况提供0这个news_id。

SELECT n.news_id, COUNT(c.com_id) + n.fb_comments_count AS total_comments
FROM news n
LEFT OUTER JOIN news_comments c ON c.news_id = n.news_id
GROUP BY n.news_id, n.fb_comments_count

答案 1 :(得分:0)

SET @rank=0;

SELECT @rank:=@rank+1 AS id,t.*
FROM(
      SELECT n.news_id,
        (COALESCE(nc.totalComments,0) + n.fb_comments_count) AS total_comments
      FROM news n
      LEFT JOIN
      (
        SELECT news_id,COUNT(*) as totalComments
        FROM news_comments
        GROUP BY news_id
      )nc
      ON n.news_id = nc.news_id
      ORDER BY total_comments desc

     ) t

SQL Fiddle Demo