如何在有条件的情况下将第一个表的行数添加到另一个表

时间:2018-11-10 14:45:37

标签: mysql sql

有两个表:

####comments####     ####news######
#cid#news_id#         #id##comm_num#  
#1##1#               #1###2#
#2##1#               #2###1#
#3##2#               #3###3#

我尝试计算并将表“ comments”中的评论数放入表“ news”中,但结果是错误的。为什么?

UPDATE news JOIN comments ON news.id = comments.news_id SET 
news.comm_num = ( SELECT COUNT( * ) 
FROM comments WHERE comments.news_id > 123)
WHERE news.id > 123

'comments.news_id'=表'news'中已评论新闻的'id'

我为特定情况写了一个可行的解决方案,但我不知道如何提出条件大于此条件的请求。

UPDATE news a 
SET comm_num = (SELECT COUNT(*) 
                FROM comments c 
                WHERE c.news_id = 123) 
WHERE a.id = 123 

2 个答案:

答案 0 :(得分:1)

只需使用相关子查询:

UPDATE news n 
    SET comm_num = (SELECT COUNT(*) 
                    FROM comments c 
                    WHERE c.news_id = n.id
                   ) ;

我不确定WHERE news.id > 123的条件是什么。

答案 1 :(得分:0)

您可以使用Derived Table获得新闻评论总数。将其重新连接到news上的news_id表中,并相应地更新值。

我们使用LEFT JOIN处理新闻没有评论的情况。并且,Coalesce()函数用于将null更改为0(在无注释的情况下)。

UPDATE news a 
LEFT JOIN (SELECT news_id, COUNT(*) AS comm_num 
           FROM comments 
           GROUP BY news_id) b 
  ON b.news_id = a.id 
SET a.comm_num = COALESCE(b.comm_num,0)

如果您只想更新news大于123的id;您可以添加以下条件:

UPDATE news a 
LEFT JOIN (SELECT news_id, COUNT(*) AS comm_num 
           FROM comments 
           WHERE news_id > 123 -- add condition to Derived Table
           GROUP BY news_id) b 
  ON b.news_id = a.id 
WHERE a.id > 123 -- add condition here also to avoid updating id <= 123
SET a.comm_num = COALESCE(b.comm_num,0)