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

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

    This is officially simple but remarkably counter-intuitive. If you're doing:

    update users set status = 'processing' where status = 'pending'
    limit 1
    

    Change it to this:

    update users set status = 'processing' where status = 'pending'
    and last_insert_id(user_id) 
    limit 1
    

    The addition of last_insert_id(user_id) in the where clause is telling MySQL to set its internal variable to the ID of the found row. When you pass a value to last_insert_id(expr) like this, it ends up returning that value, which in the case of IDs like here is always a positive integer and therefore always evaluates to true, never interfering with the where clause. This only works if some row was actually found, so remember to check affected rows. You can then get the ID in multiple ways.

    MySQL last_insert_id()

    You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.

    MySQL mysql_insert_id()

    Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement. Use this function after you have performed an INSERT statement into a table that contains an AUTO_INCREMENT field, or have used INSERT or UPDATE to set a column value with LAST_INSERT_ID(expr).

    The reason for the differences between LAST_INSERT_ID() and mysql_insert_id() is that LAST_INSERT_ID() is made easy to use in scripts while mysql_insert_id() tries to provide more exact information about what happens to the AUTO_INCREMENT column.

    PHP mysqli_insert_id()

    Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.

    Putting it all together:

    $affected_rows = DB::getAffectedRows("
        update users set status = 'processing' 
        where status = 'pending' and last_insert_id(user_id) 
        limit 1"
    );
    if ($affected_rows) {
        $user_id = DB::getInsertId();
    }
    

    (FYI that DB class is here.)

    0 讨论(0)
  • 2020-11-22 08:38

    No need for so long Mysql code. In PHP, query should look something like this:

    $updateQuery = mysql_query("UPDATE table_name SET row='value' WHERE id='$id'") or die ('Error');
    $lastUpdatedId = mysql_insert_id();
    
    0 讨论(0)
  • 2020-11-22 08:42

    Query :

    $sqlQuery = "UPDATE 
                update_table 
            SET 
                set_name = 'value' 
            WHERE 
                where_name = 'name'
            LIMIT 1;";
    

    PHP function:

    function updateAndGetId($sqlQuery)
    {
        mysql_query(str_replace("SET", "SET id = LAST_INSERT_ID(id),", $sqlQuery));
        return mysql_insert_id();
    }
    

    It's work for me ;)

    0 讨论(0)
  • 2020-11-22 08:44

    My solution is , first decide the "id" ( @uids ) with select command and after update this id with @uids .

    SET @uids := (SELECT id FROM table WHERE some = 0 LIMIT 1);
    UPDATE table SET col = 1 WHERE id = @uids;SELECT @uids;
    

    it worked on my project.

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

    0 讨论(0)
  • 2020-11-22 08:48

    If you are only doing insertions, and want one from the same session, do as per peirix's answer. If you are doing modifications, you will need to modify your database schema to store which entry was most recently updated.

    If you want the id from the last modification, which may have been from a different session (i.e. not the one that was just done by the PHP code running at present, but one done in response to a different request), you can add a TIMESTAMP column to your table called last_modified (see http://dev.mysql.com/doc/refman/5.1/en/datetime.html for information), and then when you update, set last_modified=CURRENT_TIME.

    Having set this, you can then use a query like: SELECT id FROM table ORDER BY last_modified DESC LIMIT 1; to get the most recently modified row.

    0 讨论(0)
提交回复
热议问题