2017-03-05 3 views
0

は私が私のSQLで別のテーブルからCOUNTで更新する方法

としてのみ掲載された論文をカウントするための追加 WHERE句を追加するとき、

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

しかし著者が出版された論文を更新するため、このクエリを使用

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 
) 

答えて

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

の下に、これはあなたのデータコンテンツに関連している可能性がなく、関係が副選択の結果に参加するに基づいてすることができるもの

1

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; 

これは、サブクエリで著者ごとに公開された記事の数を赤でカウントし、それを著者表に結合して列を更新します。

関連する問題