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

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

    I've found an answer to this problem :)

    SET @update_id := 0;
    UPDATE some_table SET column_name = 'value', id = (SELECT @update_id := id)
    WHERE some_other_column = 'blah' LIMIT 1; 
    SELECT @update_id;
    

    EDIT by aefxx

    This technique can be further expanded to retrieve the ID of every row affected by an update statement:

    SET @uids := null;
    UPDATE footable
       SET foo = 'bar'
     WHERE fooid > 5
       AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
    SELECT @uids;
    

    This will return a string with all the IDs concatenated by a comma.

提交回复
热议问题