Search code examples
mysqlmysql-error-1093

Update record with the biggest id value where nick = 'a'


What is the fastest way to update the record with the biggest id value where nick='a' (in one query)?

My table looks like this:

+------+--------+----+
| nick | post   | id |
+------+--------+----+
| a    | tehe   |  1 |
| a    | tehe 2 |  2 |
| a    | tehe 3 |  3 |
| b    | omg    |  4 |
| b    | omg 2  |  5 |
| a    | tehe 4 |  6 |
| b    | omg 3  |  7 |
+------+--------+----+

I tried:

update (select * from posts where nick='a' order by id limit 1) as last_id set post='tehe 4 updated';

but The target table last_id of the UPDATE is not updatable Now I know it shouldn't work.

update posts set post = 'tehe 4? updated' where id = (select id from posts where nick='a' order by id desc limit 1); 

but You can't specify target table 'posts' for update in FROM clause


Solution

  • update posts
        set post = 'tehe 4 updated'
        where nick='a'
        order by id desc limit 1