如何使用选择组在第二个表中更新表,并将自身作为MySQL中的数据源?

时间:2010-05-04 13:40:41

标签: mysql mysql-error-1093

我可以这样做:

SELECT t2.value + sum(t3.value)
FROM tableA t2, tableB t3
WHERE t2.somekey = t3.somekey
GROUP BY t3.somekey

但是怎么做?

 UPDATE tableA t1
    SET speed = (
        SELECT t2.value + sum(t3.value)
        FROM tableA t2, tableB t3
        WHERE t2.somekey = t3.somekey
        AND t1.somekey = t3.somekey
        GROUP BY t3.somekey
   )
;

MySQL认为这是非法的,因为您无法在FROM子句中为更新指定目标表t1

2 个答案:

答案 0 :(得分:8)

您可以通过重写查询来完成此操作:

UPDATE tableA t1, (
   SELECT somekey, SUM(value) value
   FROM tableB t3
   GROUP BY somekey
) t2
SET speed = t1.value + t2.value
WHERE t1.somekey = t2.somekey;

答案 1 :(得分:-1)

您正在使用MySQL的{​​{1}}扩展名,不应在此上下文中使用。

给出以下值:

GROUP BY

这个子查询:

tableA

value somekey
1     1
2     1

tableB

value somekey
3     1
4     1

将返回 SELECT t2.value + SUM(t3.value) FROM tableA t2, tableB t3 WHERE t2.somekey = t3.somekey AND t1.somekey = t3.somekey GROUP BY t3.somekey 8:它将计算9,然后为SUM(b.value) = 7添加随机值以获取给定的密钥

对于此示例数据,您希望将速度更新为哪个值?