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

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

    This is the same method as Salman A's answer, but here's the code you actually need to do it.

    First, edit your table so that it will automatically keep track of whenever a row is modified. Remove the last line if you only want to know when a row was initially inserted.

    ALTER TABLE mytable
    ADD lastmodified TIMESTAMP 
        DEFAULT CURRENT_TIMESTAMP 
        ON UPDATE CURRENT_TIMESTAMP;
    

    Then, to find out the last updated row, you can use this code.

    SELECT id FROM mytable ORDER BY lastmodified DESC LIMIT 1;
    

    This code is all lifted from MySQL vs PostgreSQL: Adding a 'Last Modified Time' Column to a Table and MySQL Manual: Sorting Rows. I just assembled it.

提交回复
热议问题