zoukankan      html  css  js  c++  java
  • MySQL查询数据表的Auto_Increment(自增id)

    1.一般数据表的id都是设置成auto_increment的,所以当插入一条记录后,可以使用下面的命令来获取最新插入记录的id值

    1 select last_insert_id();
    View Code

       注意:1. 必须是在使用Insert语句后,紧接着使用select last_insert_id()才有效,在没有使用过Insert语句的情况下,查询返回的结果为0;

                2.如果在同一条Insert语句插入多条记录,返回的结果是第一条记录对于的id,如

    1 insert into school.student 
    2 (name, age) values 
    3 ('s1', 18),
    4 ('s2', 18),
    5 ('s3', 28),
    6 ('s4', 19),
    7 ('s5', 18);
    View Code

         返回的结果是s1对于的id号。

    2. 为什么不直接使用 select max(id) from tableName;

        因为:如果手动删除了最新的数据,使用 max(id)查询的结果是当前剩下数据中最大的记录,

        而新插入数据则不一定从这个数字开始计数

    3. 所以为了准确的获取下一条插入记录的id,应该查询的是auto_increment, 对应的SQL语句如下:

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

      注意:auto_increment 可以通过 show table status where `name`='tableName' 查询得到,所以相当于一个字段了; 

                       auto_increment返回的是下一条插入记录的id值,而不是当前的最大id值

         information_schema.tables照写即可,

         table_schema="dbName",指的是数据库的名字,注意要使用双引号,

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

       

        

  • 相关阅读:
    linux之awk命令
    HDU 2097 Sky数 进制转换
    HDU 2077 汉诺塔IV
    HDU 2094 产生冠军 dfs加map容器
    HDU 2073 叠框
    HDU 2083 简易版之最短距离
    HDU 2063 过山车 二分匹配
    天梯 1014 装箱问题
    天梯 1214 线段覆盖
    天梯 1098 均分纸牌
  • 原文地址:https://www.cnblogs.com/tommy-huang/p/5602125.html
Copyright © 2011-2022 走看看