Home  >  Article  >  Database  >  How to search for auto-increment columns in mysql

How to search for auto-increment columns in mysql

coldplay.xixi
coldplay.xixiOriginal
2020-09-28 10:39:202753browse

Mysql method of searching for auto-increment columns: 1. Use [select max(id) from tablename]; 2. Use [SELECT LAST_INSERT_ID()]; 3. Use [select @@IDENTITY]; 4. [ SHOW TABLE].

How to search for auto-increment columns in mysql

Mysql method of searching for auto-increment columns:

1, select max(id) from tablename

2, SELECT LAST_INSERT_ID()

LAST_INSERT_ID is independent of table. If data is inserted into table a and then data is inserted into table b, LAST_INSERT_ID will change.

Max(id) obviously cannot be used when multiple users insert data alternately. At this time, it is time to use LAST_INSERT_ID, because LAST_INSERT_ID is based on Connection. As long as each thread uses an independent Connection object, the LAST_INSERT_ID function will return the ID of the first record generated by the latest insert or update operation of the Connection on the AUTO_INCREMENT column. This value cannot be affected by other clients (Connections), ensuring that you can retrieve your own ID without worrying about the activities of other clients, and without locking. Use a single INSERT statement to insert multiple records, LAST_INSERT_ID returns a list.

3, select @@IDENTITY;

@@identity represents the latest data inserted into the table with the identity attribute (i.e., auto-increment column). The value of the auto-increment column is a system-defined global variable. Generally, system-defined global variables start with @@, and user-defined variables start with @.

For example, there is table A, and its auto-increment column is id. After inserting a row of data into table A, if the value of the auto-increment column automatically increases to 101 after inserting the data, you can get it by selecting @@identity The value is 101. The prerequisite for using @@identity is that after performing the insert operation, the connection is not closed when executing select @@identity, otherwise the result will be a NULL value.

4, SHOW TABLE STATUS;

There is an Auto_increment field in the corresponding table name record in the result, and the value of the next auto-increment ID in it is the current The maximum self-increment ID of the table.

More related free learning recommendations: mysql tutorial(video)

The above is the detailed content of How to search for auto-increment columns in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn