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",指的是表的名字,也要使用双引号。

相关文章
相关标签/搜索