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

后端 未结 12 2253
北海茫月
北海茫月 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:27

    Hey, I just needed such a trick - I solved it in a different way, maybe it'll work for you. Note this is not a scalable solution and will be very bad for large data sets.

    Split your query into two parts -

    first, select the ids of the rows you want to update and store them in a temporary table.

    secondly, do the original update with the condition in the update statement changed to where id in temp_table.

    And to ensure concurrency, you need to lock the table before this two steps and then release the lock at the end.

    Again, this works for me, for a query which ends with limit 1, so I don't even use a temp table, but instead simply a variable to store the result of the first select.

    I prefer this method since I know I will always update only one row, and the code is straightforward.

提交回复
热议问题