我想更新最后生成的行(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
所以,我认为在执行更新等操作时我无法达到相同的故事。
我如何解决这个问题?
问候。
答案 0 :(得分:2)
您不能在子查询中引用同一个表,但您可以在JOIN中执行此操作(UPDATE
和DELETE
语句中允许这样做):
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
答案 1 :(得分: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);