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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments