mysql - How to update one table based on the count value of another table while matching ids? -
there 2 tables: articles , comments. there association between them: each comment holds article id belongs to.
----------------------------- articles ----+-------+---------------- id | title | comments_count ----+-------+---------------- 1 | aaa | 0 2 | bbb | 0 3 | ccc | 0 4 | ddd | 0 5 | eee | 0 6 | fff | 0
...
------------------------------- comments ----+-------------+------------ id | text | article_id ----+-------------+------------ 1 | aaa comment | 1 2 | aaa comment | 1 3 | fff comment | 6 4 | bbb comment | 2 5 | ddd comment | 4 6 | bbb comment | 2
the articles table further has columns holds current count of associated comments. here sqlfiddle basic setup of described tables.
after having imported bunch of articles , comments how can update comments_count on every article reflect number of associated comments?
try query:
update articles left join ( select article_id, count(*) count comments group article_id ) b on a.id = b.article_id set comments_count = coalesce(b.count, 0);
i used on sqlfiddle (had put in schema section) selecting articles showed correct counts me.
updated set correct value (you can run multiple times , after deletes, etc)
Comments
Post a Comment