The statement in MYSQL that gets the last record

  • 2020-05-09 19:29:35
  • OfStack

In MySQL, the id field of type auto_increment is used as the primary key of the table and as a foreign key of other tables to form a "master-slave table structure", which is a common use in database design. However, when specifically generating id, the order of operation is as follows: first insert the record in the main table, then get the automatically generated id, and insert the record from the secondary table based on it. One difficulty is how to get the id of the main table record when it is inserted. The usual approach is to use the "select max(id) from tablename" approach, but it is clear that this approach requires consideration of concurrency and requires an "X lock" on the main table in the transaction, until the value of max(id) is obtained, and then unlocked. This requires a lot of steps, is cumbersome, and has poor concurrency. Is there an easier way to do it? The first answer is through select LAST_INSERT_ID(). At first glance, it looks like select max(id), but it's actually thread-safe. That is, it is database connection-specific. The following are the experimental instructions:

1. Insert a record into the A table in connection 1, and the A table contains a field of type auto_increment.

2. Insert another record into the A table in join 2.

3. Results: the results obtained by executing select LAST_INSERT_ID() in connection 1 are different from the results obtained by executing select LAST_INSERT_ID() in connection 2; The result of executing select max(id) in both connections is the same.
            actually in MSSQL the difference between SCOPE_IDENTITY() and IDENT_CURRENT() is similar here. Use SCOPE_IDENTITY() to get the value of the current session inserted into an IDENTITY field, and IDENT_CURRENT() to get the maximum inserted into an IDENTITY field, without differentiating between sessions.

Note: when using select last_insert_id(), note that when multiple records are inserted once, only the id value of the first insert is obtained. You can try

insert into tb (c1, c2) values (c1value c2value), (c1value1 c2value2).. .


Related articles: