Mysql obtains the value of the auto-increment field in the table.

Source: Internet
Author: User

INSERT multiple records using a single INSERT statement. LAST_INSERT_ID only returns the value of the first inserted record. For example:

1. mysql> insert into t VALUES (NULL, 'aaa'), (NULL, 'bbbbbb'), (NULL, 'cccccc ');
2. mysql> SELECT * FROM t;
3. + ---- + ------ +
4. | id | name |
5. + ---- + ------ +
6. | 1 | Bob |
7. | 2 | aaaa |
8. | 3 | bbbb |
9. | 4 | cccc |
10. + ---- + ------ +
11. mysql> SELECT LAST_INSERT_ID ();
12. + ------------------ +
13. | LAST_INSERT_ID () |
14. + ------------------ +
15. | 2 |
16. + ------------------ +

ID 2 is generated when the first record aaaa is inserted.

LAST_INSERT_ID is table-independent. If you insert data to table a and then insert data to table B, LAST_INSERT_ID will change.

Generally, you can obtain the id of the inserted data by using select max (id) from table.

But in the case of multiple threads, it won't work. Max (id) is obviously unavailable when multiple users insert data alternately.

This
LAST_INSERT_ID should be used, because LAST_INSERT_ID is based on Connection, as long as each thread uses an independent
Connection object. The LAST_INSERT_ID function returns the latest insert or
The ID of the first record generated by the update operation. This value cannot be affected by other clients (connections), so that you can retrieve your ID.
You don't have to worry about the activities of other clients, and do not need to lock them.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.