0

我想更新最后生成的行(该max(id)行。

我试过这段代码,但它不起作用

update person t1
set t1.age = 25
where t1.id = (select max(t2.id)  from person t2
            where t2.address = 'LA, California');

MySQL 告诉我:Error Code: 1093. You can't specify target table 't1' for update in FROM clause

所以,我想在执行更新等操作时我无法达到相同的故事。

我该如何解决这个问题?

问候。

4

2 回答 2

2

您不能在子查询中引用同一个表,但您可以在 JOIN 中执行它(在UPDATEandDELETE语句中是允许的):

UPDATE person a
JOIN   (SELECT MAX(id) AS id FROM person WHERE address = 'LA, California') b
       ON a.id = b.id
SET    a.age = 25

另一种方法是使用ORDER BY/LIMIT技术:

UPDATE   person
SET      age = 25
WHERE    address = 'LA, California'
ORDER BY id DESC
LIMIT    1
于 2012-07-30T10:12:52.007 回答
2

您可以尝试如下:

UPDATE person t1
    INNER JOIN (SELECT MAX(id) AS id  FROM person
            WHERE t2.address = 'LA, California') t2
        ON t1.id = t2.id
SET t1.age = 25;

或者

SELECT MAX(t2.id)
INTO @var_max_id
FROM person t2
WHERE t2.address = 'LA, California';

UPDATE person t1
SET t1.age = 25
WHERE t1.id = IFNULL(@var_max_id, -1);
于 2012-07-30T10:14:24.180 回答