Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update fields that is the aggregate result of another table in MySQL?

UPDATE  a JOIN  b ON a.app_id=b.app_id GROUP BY a.app_id SET 

remark_avg=AVG(b.score),remark_count=COUNT(b.id);

The above is basically what I want to do,but it's not a valid MySQL statement,how to write it correctly?

like image 756
gdb Avatar asked Apr 22 '11 03:04

gdb


1 Answers

    UPDATE a
INNER JOIN (SELECT AVG(b.score) avg_score,
                   COUNT(b.id) cnt_id,
                   b.app_id
              FROM b
          GROUP BY b.app_id) x ON x.app_id = a.app_id
       SET remark_avg = x.avg_score,
           remark_count = x.cnt_id;
like image 154
zerkms Avatar answered Oct 16 '22 20:10

zerkms