AUTO_INCREMENT 属性可以用来为新行生成一个唯一的标识。它有如下特性:
- 自增
 - 每张表一个
 - 必须是索引的一部分
 
AUTO_INCREMENT 是实例启动时,取当前表的最大值,然后 +1 即为下次自增的值(MAX + 1)。
AUTO_INCREMENT 要如何使用,参考如下例子:
-- 如果我们在创建表时,指定某列是AUTO_INCREMENT,且没有设置索引,就会报如下错误。mysql> create table t4(a int auto_increment);ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key-- 指定列为key后才有效,一般我们指定为PRIMARY KEYmysql> create table t4(a int auto_increment primary key);Query OK, 0 rows affected (0.11 sec)-- 插入NULL值mysql> insert into t4 values(NULL);Query OK, 1 row affected (0.03 sec)mysql> select * from t4;+---+| a |+---+| 1 | -- 插入NULL值,便可以让其自增,且默认从1开始+---+1 row in set (0.00 sec)-- 插入0值,还是自增的,自增为2-- 数字0这个值比较特殊,插入0和插入NULL的效果是一样的,都是代表自增mysql> insert into t4 values(0);Query OK, 1 row affected (0.03 sec)mysql> select * from t4;+---+| a |+---+| 1 || 2 | -- 插入0 ,自增长为2+---+2 rows in set (0.00 sec)-- 插入-1,这个是可以插入指定值的mysql> insert into t4 values(-1);Query OK, 1 row affected (0.02 sec)mysql> select * from t4;+----+| a |+----+| -1 | -- 刚刚插入的-1| 1 || 2 |+----+3 rows in set (0.00 sec)-- 插入NULL值,这里是插入0还是3?-- 是3,因为插入的值没有大于下一个自增的值,它还是插入自增值mysql> insert into t4 values(NULL);Query OK, 1 row affected (0.02 sec)mysql> select * from t4;+----+| a |+----+| -1 || 1 || 2 || 3 | -- 刚刚插入NULL, 自增为3+----+4 rows in set (0.00 sec)-- 插入字符0mysql> insert into t4 values('0');Query OK, 1 row affected (0.04 sec)mysql> select * from t4;+----+| a |+----+| -1 || 1 || 2 || 3 || 4 | -- 插入字符'0'后, 自增长为4+----+5 rows in set (0.00 sec)-- 更新为0mysql> update t4 set a = 0 where a = -1;Query OK, 1 row affected (0.03 sec)Rows matched: 1 Changed: 1 Warnings: 0mysql> select * from t4;+---+| a |+---+| 0 | -- 原来的-1更新为0| 1 || 2 || 3 || 4 |+---+5 rows in set (0.00 sec)-- 插入NULL 100 NULLmysql> insert into t4 values(NULL), (100), (NULL);Query OK, 3 rows affected (0.02 sec)Records: 3 Duplicates: 0 Warnings: 0mysql> select * from t4;+-----+| a |+-----+| 0 || 1 || 2 || 3 || 4 || 5 | -- 第一个NULL| 100 | -- 100| 101 | -- 第二个NULL, 按当前最大的值+1来设置,之前是100,所以这里101+-----+8 rows in set (0.00 sec)mysql> insert into t4 values(99); -- 插入99Query OK, 1 row affected (0.02 sec)mysql> select * from t4;+-----+| a |+-----+| 0 || 1 || 2 || 3 || 4 || 5 || 99 | -- 刚刚插入的 99| 100 || 101 |+-----+9 rows in set (0.00 sec)
作者:殷建卫 链接:https://www.yuque.com/yinjianwei/vyrvkf/gywsex 来源:殷建卫 - 架构笔记 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
