[英]MySQL join / sum value from one table colum with a count values from another
表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|
-----------------------------------
提前致謝! :)
一個簡單的聯接和group by可以使用COUNT()來計算您的所有評論。 然后只需將其添加到fb_comment_count。 我們使用LEFT JOIN
來確保它還包含news_comments中未出現的news_id,並將COUNT()僅應用於c.com_id,以確保在沒有news_comments的news_comments的情況下,該值將為0。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.