2017-03-05 27 views
0

我用這個查詢更新由作者發表如何通過COUNT從另一個表在我的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(*)未正確計算已發佈文章的數量。

回答

1

如果你更改查詢像下面

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

這可能與您的數據內容,但關係可以基於連接的子查詢結果

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 
1

嘗試使用UPDATEJOIN

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; 

它發現過濾對每個作者在子查詢中發佈的文章進行紅色計數,然後將其與作者表一起加入以更新其列。

相關問題