MySQL query data table Auto_Increment (increment id)

1. General data table id is set to auto_increment, so when a record is inserted, the following command can be used to obtain the value of the newly inserted record id

select last_insert_id();

  

   Note: 1 must be after using Insert statement, followed by the use of select last_insert_id () is only valid in the case did not use the Insert statement, the result of the query returns 0;.

            2. If insert multiple records in the same Insert statement, the result is returned to the first record id, such as

insert into school.student 
(name, age) values 
('s1', 18),
('s2', 18),
('s3', 28),
('s4', 19),
('s5', 18);

  

   The result is returned to the id s1.

2. Why not just use select max (id) from tableName;

    Because: If you manually delete the latest data, use the max (id) the results of the query is currently the largest remaining data records,

    The new data is inserted from this figure does not necessarily start counting

3. Therefore, in order to obtain an accurate record of the next insert id, that query is auto_increment, the corresponding SQL statement is as follows:

SELECT auto_increment FROM information_schema.tables where table_schema="dbName" and table_name="tableName";

  

  Note: auto_increment inquiries can show table status where `name` = 'tableName', so the equivalent of a field; 

                   auto_increment returns the next record is inserted id value instead of the maximum current value id

     information_schema.tables as to write,

     table_schema = "dbName", refers to the name of the database, note that you want to use double quotes,

       table_name = "tableName", refers to the name of the table, but also use double quotes.

Guess you like

Origin www.cnblogs.com/guohu/p/10984278.html