简体   繁体   中英

MySQL join / sum value from one table colum with a count values from another

Table 1 - "news"

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

Table 2 - "news_comments"

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

I need to get total comments sum for every single news, where facebook comments count from the first table and total count of comments for every specific news from the other table, are counted together.

Like this - "Total comments":

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

Thanks in advance! :)

A simple join and a group by can count all your comments with COUNT(). Then simply add this to the fb_comment_count. We use a LEFT JOIN to make sure it also includes news_id's that don't occur in news_comments, and apply the COUNT() only to c.com_id, to ensure this will give 0 for these situations when there are no news_comments for this 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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM