Mysql in PHP - how to update only one row in table but with greatest id number

前端 未结 9 2065

I am trying to update fields in my DB, but got stuck with such a simple problem: I want to update just one row in the table with the biggest id number. I would do something like

9条回答
  •  你的背包
    2021-02-19 03:38

    UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table) 
    

    This query will return an error as you can not do a SELECT subquery from the same table you're updating.

    Try using this:

    UPDATE table SET name='test_name' WHERE id = (
        SELECT uid FROM (
            SELECT MAX(id) FROM table AS t
        ) AS tmp
    )
    

    This creates a temporary table, which allows using same table for UPDATE and SELECT, but at the cost of performance.

提交回复
热议问题