使用另一个表中列的平均值

时间:2013-07-11 14:33:13

标签: mysql group-by sql-update average

我有两张桌子:

CARMAKES
id, name, avg_sold_for

SALES
carmake_id, price

我想要做的是使用单个SQL语句执行以下操作: 对于CARMAKES中的所有行,avg_sold_for字段应显示SALES中所有价格字段的平均值,其中carmake_id与CARMAKES中的给定ID匹配。

以示例:

CARMAKES
id, name, avg_sold_for
0, "Toyota", 0
1, "Nissan", 0

SALES
carmake_id, price
0, 10
1, 20
0, 30
0, 20

我想将CARMAKES表更新为

CARMAKES
id, name, avg_sold_for
0, "Toyota", 20
1, "Nissan", 20

1 个答案:

答案 0 :(得分:0)

试试这个:

UPDATE CARMAKES
SET avg_sold_for = (SELECT SUM(price) / COUNT(carmake_id) 
                    FROM SALES WHERE CARMAKES.id = SALES.carmake_id)

UPDATE CARMAKES C 
INNER JOIN (SELECT carmake_id, (SUM(price) / COUNT(carmake_id)) avg_sold_for
            FROM SALES GROUP BY carmake_id) A ON C.id = A.carmake_id
SET C.avg_sold_for = A.avg_sold_for