在MySQL中使用subselect更新

时间:2011-08-16 23:29:51

标签: mysql

如何让以下语句在MySQL中运行?

UPDATE my_table t1 SET column_1 = 
(SELECT column_1 FROM my_table t2 WHERE t2.id = (t1.id - 1))
WHERE t1.type = 2

我收到"You can't specify target table 't1' for update in FROM clause"错误。

2 个答案:

答案 0 :(得分:4)

您可以使用加入进行更新:

UPDATE my_table t1
    JOIN my_table t2 ON t2.id = t1.id - 1
SET t1.column_1 = t2.column_1
WHERE t1.type = 2

答案 1 :(得分:-1)

尝试删除“my_table”:)

UPDATE t1 SET column_1 = 
(SELECT column_1 FROM t2 WHERE t2.id = (t1.id - 1))
WHERE t1.type = 2