mysql怎么实现表自增 mysql设置自增列( 三 )


根据要插入的值和当前自增值的大小关系,自增值的变更结果也会有所不同 。假设,某次要插入的值是X,当前的自增值是Y 。
1. 如果XY,那么这个表的自增值不变;
2. 如果X≥Y,就需要把当前自增值修改为 新的自增值。
新的自增值生成算法是:从auto_increment_offset开始,以auto_increment_increment为步长 , 持续叠加,直到找到第一个大于X的值,作为新的自增值 。
Insert、update、delete操作会让id不连续 。
Delete、update:删除中间数据 , 会造成空动,而修改自增id值,也会造成空洞(这个很少) 。
Insert:插入报错(唯一键冲突与事务回滚),会造成空洞,因为这时候自增id已经分配出去了,新的自增值已经生成,如下面例子:
[root@localhost][test1] select * fromt;
+----+------+
| id | name |
+----+------+
|1| aaa|
|2| aaa|
|3| aaa|
|4| aaa|
+----+------+
4 rows in set (0.00 sec)
[root@localhost][test1] selectAuto_increment from information_schema.tables where table_name='t';
+----------------+
| Auto_increment |
+----------------+
|5 |
+----------------+
1 row in set (0.00 sec)
[root@localhost][test1] begin;
Query OK, 0 rows affected (0.00 sec)
[root@localhost][test1] insert intot(name) values('aaa');
Query OK, 1 row affected (0.00 sec)
[root@localhost][test1] select * fromt;
+----+------+
| id | name |
+----+------+
|1| aaa|
|2| aaa|
|3| aaa|
|4| aaa|
|5| aaa|
+----+------+
5 rows in set (0.00 sec)
【mysql怎么实现表自增 mysql设置自增列】[root@localhost][test1] selectAuto_increment from information_schema.tables where table_name='t';
+----------------+
| Auto_increment |
+----------------+
|6 |
+----------------+
1 row in set (0.00 sec)
[root@localhost][test1] rollback;
Query OK, 0 rows affected (0.00 sec)
[root@localhost][test1] selectAuto_increment from information_schema.tables where table_name='t';
+----------------+
| Auto_increment |
+----------------+
|6 |
+----------------+
1 row in set (0.01 sec)
[root@localhost][test1] select * fromt;
+----+------+
| id | name |
+----+------+
|1| aaa|
|2| aaa|
|3| aaa|
|4| aaa|
+----+------+
4 rows in set (0.00 sec)
可以看到,虽然事务回滚了,但自增id已经回不到从前啦,唯一键冲突也是这样的 , 这里就不做测试了 。
在批量插入时(insert select等),也存在空洞的问题 。看下面实验:
[root@localhost][test1] select * fromt;
+----+------+
| id | name |
+----+------+
|1| aaa|
|2| aaa|
|3| aaa|
|4| aaa|
+----+------+
4 rows in set (0.00 sec)
[root@localhost][test1] selectAuto_increment from information_schema.tables where table_name='t';
+----------------+
| Auto_increment |
+----------------+
|5 |
+----------------+
1 row in set (0.00 sec)
[root@localhost][test1] insert intot(name) select name from t;
Query OK, 4 rows affected (0.04 sec)
Records: 4 Duplicates: 0Warnings: 0
[root@localhost][test1] select * fromt;
+----+------+
| id | name |
+----+------+
|1| aaa|
|2| aaa|
|3| aaa|
|4| aaa|
|5| aaa|
|6| aaa|
|7| aaa|
|8| aaa|
+----+------+
8 rows in set (0.00 sec)
[root@localhost][test1] selectAuto_increment from information_schema.tables where table_name='t';
+----------------+
| Auto_increment |

推荐阅读