如何更新MySQL中另一个表的聚合结果的字段?

时间:2011-04-22 03:43:23

标签: mysql aggregate-functions

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

以上基本上是我想做的,但它不是一个有效的MySQL语句,如何正确编写它?

1 个答案:

答案 0 :(得分:20)

    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;