1

我有两张桌子:

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
4

1 回答 1

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 
于 2013-07-11T15:07:11.860 回答