mysql increment_Mysql数据库之auto_increment
一、概述
在数据库应用中,我们经常需要用到自动递增的唯一编号来标识记录。在MySQL中,可通过数据列的auto_increment属性来自动生成。可在建表时可用“auto_increment=n”选项来指定一个自增的初始值。可用“alter table table_name auto_increment=n”命令来重设自增的起始值,当然在设置的时候Mysql会取数据表中auto_increment列的最大值 + 1与n中的较大者作为新的auto_increment值。
Myql的auto_increment属性具有以下特性:
具有auto_increment属性的数据列应该是一个正数序列,如果把该数据列声明为UNSIGNED,这样序列的编号个数可增加一倍。比如tinyint数据列的最大编号是127,如果加上UNSIGNED,那么最大编号变为255
auto_increment数据列必须有唯一索引,以避免序号重复;必须具备NOT NULL属性
实际应用中发现,在delete掉某张innoDB表的全部数据并重启Mysql会导致该表的auto_increment列变为1。特测试多种情况下auto_increment列的变化并记录如下。
二、实验
1、innoDB与MyISAM对比
(1)首先,创建一张引擎为innoDB的表测试一下delete掉所有数据然后重启Mysql之后,auto_increment的情况:
mysql> CREATE TABLE`table1` (-> `id` bigint(20) NOT NULLauto_increment,-> `create_time` datetime DEFAULT NULL,-> PRIMARY KEY(`id`)-> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK,0rows affected
mysql> insert into table1(create_time) values(now());
Query OK,1row affected
mysql> insert into table1(create_time) values(now());
Query OK,1row affected
mysql> insert into table1(create_time) values(now());
Query OK,1row affected
mysql> insert into table1(create_time) values(now());
Query OK,1row affected
mysql> insert into table1(create_time) values(now());
Query OK,1row affected
mysql> select * fromtable1;+----+---------------------+
| id | create_time |
+----+---------------------+
| 1 | 2017-02-28 16:25:11 |
| 2 | 2017-02-28 16:25:21 |
| 3 | 2017-02-28 16:25:23 |
| 4 | 2017-02-28 16:25:23 |
| 5 | 2017-02-28 16:25:24 |
| 6 | 2017-02-28 16:25:26 |
+----+---------------------+
6 rows in setmysql> delete fromtable1;
Query OK,6rows affected
mysql> select * fromtable1;
Emptysetmysql> select auto_increment from information_schema.tables where table_schema = database() and table_name='table1';+----------------+
| auto_increment |
+----------------+
| 7 |
+----------------+
1 row in set
可见,执行delete操作清空表之后,表table1的auto_increment值仍然是正常的。重启数据库之后:
mysql> select auto_increment from information_schema.tables where table_schema = database() and table_name='table1';+----------------+
| auto_increment |
+----------------+
|
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
