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

前端 未结 9 2030

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:36

    Select the max id first, then update.

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-19 03:45

    Using PHP I tend to do run a mysqli_num_rows then put the result into a variable, then do an UPDATE statement saying where ID = the newly created variable. Some people have posted there is no need to use LIMIT 1 on the end however I like to do this as it doesn't cause any trivial delay but could prevent any unforeseen actions from being taken.

    If you have only just inserted the row you can use PHP's mysqli_insert_id function to return this id automatically to you without needing to run the mysqli_num_rows query.

    0 讨论(0)
  • 2021-02-19 03:48
    UPDATE table_NAME
    SET COLUMN_NAME='COLUMN_VALUE' 
    ORDER BY ID 
    DESC LIMIT 1;
    

    Because you can't use SELECT IN DELETE OR UPDATE CLAUSE.ORDER BY ID DESC LIMIT 1. This gives you ID's which have maximum value MAX(ID) like you tried to do. But MAX(ID) will not work.

    0 讨论(0)
  • 2021-02-19 03:49

    Old Question, but for anyone coming across this you might also be able to do this:

    UPDATE
         `table_name` a
    JOIN (SELECT MAX(`id`) AS `maxid` FROM `table_name`) b ON (b.`maxid` = a.`id`)
    SET a.`name` = 'test_name';
    
    0 讨论(0)
  • 2021-02-19 03:53

    The use of MAX() is not possible at this position. But you can do this:

    UPDATE table SET name='test_name' ORDER BY id DESC LIMIT 1;
    
    0 讨论(0)
提交回复
热议问题