用COUNT个其他字段更新列是SQL吗?

| 大家好,我设置了以下表格:
Articles:
ID | TITLE | CONTENT | USER | NUM_COMMENTS

COMMENTS
ID | ARTICLE_ID | TEXT
我需要一条sql语句,该语句使用对文章的评论计数来更新articles表的NUM_Comments字段,例如:
update articles a, comments f 
set a.num_comments =  COUNT(f.`id`)
where f.article_id = a.id
上面的sql无法正常工作,并且出现“使用组功能无效”错误。我在这里使用MySQL。     
已邀请:
您不能在更新语句中加入。它应该是
update articles
set num_comments =
(select count (*) from comments
where comments.article_id = articles.id)
这将更新整个文章表,而这可能不是您想要的。如果您只打算更新一篇文章,则在子查询之后添加一个\'where \'子句。     
这应该工作。
UPDATE articles a SET num_comments = 
(SELECT COUNT(*) FROM comments c WHERE c.article_id = a.id)
但是当发布评论时,我只希望更新一条记录:
UPDATE articles a SET num_comments = 
(SELECT COUNT(*) FROM comments c WHERE c.article_id = 100) WHERE a.id = 100
    
count(*)可能会有一些问题,尤其是count和(*)之间的空格... 所以在sqlite上运行sql,pgsql将是:
update articles 
  set num_comments = 
    (select count(id) from comments 
     where comments.article_id = articles.id)
    
要仅根据列数进行更新,您可以执行以下操作:
update articles,
 (select count (*) 
  from comments
  where comments.article_id = articles.id) as newtotals
set articles.num_comments = newtotals.count;
或...如果您遇到需要滚动计数的情况:
update articles,
 (select (count (*)) + (articles.num_comments) as count 
  from comments
  join articles on 
    comments.article_id = articles.id
  group by articles.id) as newtotals
set articles.num_comments = newtotals.count;
    
您不能以通用的内部联接方式进行操作。但您可以通过以下方式另一种方式: 1-从商品表中选择所有ID 2-迭代它们并执行以下命令 更新文章集NUM_COMMENTS =(从id = $ id的注释中选择count(id))id = $ id 为了进一步增强它,在第一个选择中不要选择所有值,尤其是在该表太大时,您需要迭代文章并每次迭代获得1000条记录。这样,您将维护数据库池中健康的数据库线程,还可以节省带宽。     

要回复问题请先登录注册