MySQL:更新具有最大值的'where'子句的表

时间:2012-07-30 10:09:33

标签: mysql

我想更新最后生成的行(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

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

我如何解决这个问题?

问候。

2 个答案:

答案 0 :(得分:2)

您不能在子查询中引用同一个表,但您可以在JOIN中执行此操作(UPDATEDELETE语句中允许这样做):

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);