[英]How to update by COUNT from another table in my sql
我使用此查询来更新作者发表的文章
UPDATE authors SET total_articles =
(
SELECT COUNT(*) FROM articles
WHERE articles.author_id=authors.author_id
GROUP BY author_id
)
但是,当我添加其他WHERE
子句以仅将已发布的文章计为
UPDATE authors SET published_articles =
(
SELECT COUNT(*) FROM articles
WHERE articles.author_id=authors.author_id AND articles.status='published'
GROUP BY author_id
)
count(*)
不能正确计算已发表文章的数量。
如果您更改查询如下所示该怎么办
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
)
这可能与您的数据内容有关,但是该关系可能基于子选择结果的联接
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
尝试将UPDATE
与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;
它在子查询中查找每个作者的已发布文章的已过滤计数,然后将其与author表联接以更新其列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.