如何根据条件将第一个表的行数添加到另一个表中

e3bfsja2  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(289)

有两个表:


#### 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\u id'=表'news'中已评论新闻的'id'
我为特定情况编写了一个有效的解决方案,但我不知道如何在条件大于的情况下发出请求。

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

huwehgph1#

您可以使用派生表获取新闻上的评论总数。把这个放回原处 news 桌上的table 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 哪里 id 大于123;您可以添加以下条件:

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)
w3nuxt5m

w3nuxt5m2#

只需使用相关子查询:

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

我不确定情况如何 WHERE news.id > 123 是给你的。

相关问题