MySQL查詢數據表的Auto_Increment(自增id)

1.通常數據表的id都是設置成auto_increment的,因此當插入一條記錄後,能夠使用下面的命令來獲取最新插入記錄的id值sql

select last_insert_id();

  

   注意:1. 必須是在使用Insert語句後,緊接着使用select last_insert_id()纔有效,在沒有使用過Insert語句的狀況下,查詢返回的結果爲0;數據庫

            2.若是在同一條Insert語句插入多條記錄,返回的結果是第一條記錄對於的id,如orm

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

  

   返回的結果是s1對於的id號。blog

2. 爲何不直接使用 select max(id) from tableName;rem

    由於:若是手動刪除了最新的數據,使用 max(id)查詢的結果是當前剩下數據中最大的記錄,io

    而新插入數據則不必定從這個數字開始計數table

3. 因此爲了準確的獲取下一條插入記錄的id,應該查詢的是auto_increment, 對應的SQL語句以下:ast

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

  

  注意:auto_increment 能夠經過 show table status where `name`='tableName' 查詢獲得,因此至關於一個字段了; form

                   auto_increment返回的是下一條插入記錄的id值,而不是當前的最大id值class

     information_schema.tables照寫便可,

     table_schema="dbName",指的是數據庫的名字,注意要使用雙引號,

       table_name="tableName",指的是表的名字,也要使用雙引號。

相關文章
相關標籤/搜索