簡體   English   中英

用其他字段的 COUNT 更新一列是 SQL?

[英]Update a column with a COUNT of other fields is SQL?

我設置了以下表格:

Articles:
ID | TITLE | CONTENT | USER | NUM_COMMENTS

COMMENTS
ID | ARTICLE_ID | TEXT

我需要一個 sql 語句,它使用針對文章的評論計數更新文章表的 NUM_Comments 字段,例如:

update articles a, comments f 
set a.num_comments =  COUNT(f.`id`)
where f.article_id = a.id

上面的 sql 不起作用,我收到 Invalid Use fo Group function 錯誤。 我在這里使用 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

要僅根據列數進行更新,您可以執行以下操作:

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;

count (*) 可能有一些問題,尤其是 count 和 (*) 之間的空格...

所以在 sqlite 上工作 sql,pgsql 將是:

update articles 
  set num_comments = 
    (select count(id) from comments 
     where comments.article_id = articles.id)

您不能以通用的內部連接方式進行操作。 但您可以通過以下方式以另一種方式做到這一點:

1- Select 文章表中的所有 id

2-迭代它們並執行以下命令

更新文章集 NUM_COMMENTS = (select count(id) from comments where id = $id) where id = $id

為了進一步增強它,在第一個 select 不要 select 所有值,特別是當該表太大時,您需要迭代文章並每次迭代獲得 1000 條記錄。 這樣,您將從數據庫池中維護一個健康的數據庫線程,並且還可以節省帶寬。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM