How to get ID of the last updated row in MySQL?

后端 未结 12 2247
北海茫月
北海茫月 2020-11-22 08:10

How do I get the ID of the last updated row in MySQL using PHP?

12条回答
  •  有刺的猬
    2020-11-22 08:25

    Hm, I am surprised that among the answers I do not see the easiest solution.

    Suppose, item_id is an integer identity column in items table and you update rows with the following statement:

    UPDATE items
    SET qwe = 'qwe'
    WHERE asd = 'asd';
    

    Then, to know the latest affected row right after the statement, you should slightly update the statement into the following:

    UPDATE items
    SET qwe = 'qwe',
        item_id=LAST_INSERT_ID(item_id)
    WHERE asd = 'asd';
    SELECT LAST_INSERT_ID();
    

    If you need to update only really changed row, you would need to add a conditional update of the item_id through the LAST_INSERT_ID checking if the data is going to change in the row.

提交回复
热议问题