当前位置: 移动技术网 > IT编程>数据库>Mysql > 解析mysql中的auto_increment的问题

解析mysql中的auto_increment的问题

2017年12月12日  | 移动技术网IT编程  | 我要评论

今儿在逛论坛时,发现一个看似很简单的问题,却引起了大家的广泛关注:
这是一道很早的面试题:
一张表,里面有id自增主键,当insert了17条记录之后,删除了第15,16,17条记录,再把mysql重启,再insert一条记录,这条记录的id是18还是15 。
答案:

如果表的类型是myisam,那么是18。
因为myisam表会把自增主键的最大id记录到数据文件里,重启mysql自增主键的最大id也不会丢失。
如果表的类型是innodb,那么是15。
innodb表只是把自增主键的最大id记录到内存中,所以重启数据库或者是对表进行optimize操作,都会导致最大id丢失。

自己也做了个实验,结果证实了上面的说法。真是惭愧啊,看似简单的问题自己也打错了。

复制代码 代码如下:

mysql> select * from test1;
+----+-----------+
| id | name      |
+----+-----------+
|  1 | 陈兵辉    |
|  2 | chen      |
|  3 | chen      |
|  4 | chen      |
|  5 | chen      |
|  6 | chen      |
|  7 | chen      |
|  8 | chen      |
|  9 | chen      |
| 10 | chen      |
| 11 | chen      |
+----+-----------+
11 rows in set (0.00 sec)

mysql> delete from test1 where id in (10,11,9);
query ok, 3 rows affected (0.03 sec)

mysql> show create table test1;
 create table `test1` (
  `id` int(11) not null auto_increment,
  `name` varchar(10) default null,
  primary key  (`id`)
) engine=innodb auto_increment=<span style="color: #ff0000">12</span> default charset=utf8 |
mysql> exit;
bye
[root@fsailing1 ~]# service mysqld restart
停止 mysql:                                               [确定]
启动 mysql:                                               [确定]
[root@fsailing1 ~]# mysql -uroot -p
enter password:
welcome to the mysql monitor.  commands end with ; or \g.
your mysql connection id is 2
server version: 5.0.95 source distribution
copyright (c) 2000, 2011, oracle and/or its affiliates. all rights reserved.

oracle is a registered trademark of oracle corporation and/or its
affiliates. other names may be trademarks of their respective
owners.

type 'help;' or '\h' for help. type '\c' to clear the current input statement.

mysql> use test;
reading table information for completion of table and column names
you can turn off this feature to get a quicker startup with -a

database changed
mysql> show create table test1;
| create table `test1` (
  `id` int(11) not null auto_increment,
  `name` varchar(10) default null,
  primary key  (`id`)
) engine=innodb auto_increment=<span style="color: #ff0000">9</span> default charset=utf8 |


2,另外还有一个就是获取当前数据库表的自增字段数。
复制代码 代码如下:

mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                0 |
+------------------+
1 row in set (0.00 sec)

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网