简体   繁体   中英

How to update by COUNT from another table in my sql

I use this query for updating the articles published by authors

UPDATE authors SET total_articles = 
(
SELECT COUNT(*) FROM articles 
WHERE articles.author_id=authors.author_id  
GROUP BY author_id
)

However, when I add an additional WHERE clause to count only published articles as

UPDATE authors SET published_articles = 
(
SELECT COUNT(*) FROM articles 
WHERE articles.author_id=authors.author_id AND articles.status='published' 
GROUP BY author_id
)

The count(*) does not correctly count the number of published articles.

what if you change the query like below

UPDATE authors SET published_articles = 
(
SELECT COUNT(*) FROM articles a
JOIN authors au ON a.author_id = au.author_id 
WHERE a.status='published' 
GROUP BY a.author_id
)

this could be related to your data content but the relation could be based on a join on subselect result

  UPDATE authors 
  INNER JOIN (
  SELECT articles.author_id , COUNT(*) as num 
  FROM articles 
  WHERE articles.author_id=authors.author_id 
  AND articles.status='published' 
  GROUP BY author_id
  ) t on t.author_id=authors.author_id 
  SET published_articles = t.num

Try using the UPDATE with JOIN :

update authors a
join (
    select author_id,
        count(*) cnt
    from articles
    where status = 'published'
    group by author_id
    ) ar
    on ar.author_id = a.author_id
set a.total_articles = ar.cnt;

It finds filtered count of published articles per author in subquery and then join it with author table to update it's column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM