1

我需要根据另一个表中某些值的总和来更新表中的多条记录。这是我的查询:

UPDATE aallinnot2 c SET c.Energ_Kcal = ( SELECT d.id1, SUM( c.Energ_Kcal) 
FROM aaingred a
LEFT JOIN aaweight b ON a.unit = b.uni
LEFT JOIN aallinnot2 c ON a.mfdfsds = c.NDB_No
LEFT JOIN aalinfsds d ON a.fsdsnum = d.id1
WHERE d.own_id =42
GROUP BY id1 ) 
WHERE c.NDB_No
IN (    SELECT DISTINCT  `fsdsnum` 
FROM  `aaingred` 
WHERE  `usernum` LIKE  '42'
)

MySQL said: 

#1093 - You can't specify target table 'c' for update in FROM clause 

不幸的是,如果不引用目标表'c',我不知道如何获取我的值!有解决方法吗?

4

2 回答 2

1

凭借疯狂的表/列名称和难以理解的逻辑,这可能是我见过的最丑陋的查询。恭喜。:)

我认为以下应该有效(或这种方法)。主要问题是解开 group-by 表达式——您需要为数据库引擎提供一个数据集,其中目标表中的每一行都连接到包含该行更新值的集合。因此,在这里,选择子查询中的新值,然后将该子查询连接到原始表。

编辑修正了一些语法

    UPDATE 
    (
    SELECT d.id1, SUM (c.Energ_Kcal) AS Sum_Energ_Kcal
        FROM aaingred a
            LEFT JOIN aaweight b ON a.unit = b.uni
            LEFT JOIN aallinnot2 c ON a.mfdfsds = c.NDB_No
            LEFT JOIN aalinfsds d ON a.fsdsnum = d.id1
        WHERE d.own_id =42
        GROUP BY id1
    ) d
    ,aaingred a, aallinnot2 d
    SET Energ_Kcal = d.Sum_Energ_Kcal
    WHERE d.id1 = a.fsdsnum
    AND a.mfdfsds = aallinnot2.NDB_No
    AND c.NDB_No IN (
        SELECT DISTINCT  `fsdsnum` 
        FROM  `aaingred` 
        WHERE  `usernum` LIKE  '42'
    );
于 2012-04-26T20:12:33.860 回答
0

我不确定 mysql,但使用 SQL Server,语句将是这样的:

    UPDATE aallinnot2 
    SET Energ_Kcal = ( 
    SELECT SUM( c.Energ_Kcal) 
    FROM aaingred a
    LEFT JOIN aaweight b ON a.unit = b.uni
    LEFT JOIN aallinnot2 c ON a.mfdfsds = c.NDB_No
    LEFT JOIN aalinfsds d ON a.fsdsnum = d.id1
    WHERE d.own_id =42) 
    WHERE c.NDB_No
    IN (    SELECT DISTINCT  `fsdsnum` 
    FROM  `aaingred` 
    WHERE  `usernum` LIKE  '42')

您不能在子句中为要更新的表起别名UPDATE,但可以在FROM子句中。

于 2012-04-26T18:12:06.390 回答