Advertisement

mysql 自动增值列_【Mysql 学习】自动增长列

阅读量:

--对于innodb表,自动增长列必须是索引。如果是组合索引,也必须是前导列。

mysql> create table innodb_auto

-> ( id1 int not null auto_increment,

-> id2 int not null,

-> val varchar(10),

-> index(id2,id1)

-> ) engine=innodb;

ERROR 1075 (42000): 无效的表格定义; 只能有一个自动生成字段,并且该字段必须被指定为主键

在myisam表中,在使用组合索引的情况下,默认情况下允许将自动增长列为该组合索引中的其他字段。插入新记录后,默认情况下会按该组合索引前几项排序递增的方式填充自动增长列值。如下的实验验证了这一点。

--创建一个myisam表

mysql> create table myisam_auto

-> ( id1 int not null auto_increment,

-> id2 int not null,

-> val varchar(10),

-> index(id2,id1)

-> ) engine=myisam;

Query OK, 0 rows affected (0.11 sec)

mysql> insert into myisam_auto(id2,val) values(2,'2'),(3,'3'),(4,'4'),(5,'5'),(2,'2'),(3,'3'),(4,'4');

Query OK, 7 rows affected (0.00 sec)

Records: 7 Duplicates: 0 Warnings: 0

mysql> select * from myisam_auto;

+-----+-----+------+

|id1|id2|val|

+-----+-----+------+

|1|2|2|

|1|3|3|

|1|4|4|

|1|5|5|

|2|2|2|

|2|3|3|

|2|4|4|

+-----+-----+------+

7 rows in set (0.00 sec)

mysql> insert into myisam_auto(id2,val) values(3,'3'),(4,'4');

Query OK, 2 rows affected (0.00 sec)

Records: 2 Duplicates: 0 Warnings: 0

mysql> select * from myisam_auto;

+-----+-----+------+

|id1|id2|val|

+-----+-----+------+

|1|2|2|

|1|3|3|

|1|4|4|

|1|5|5|

|2|2|2|

|2|3|3|

|2|4|4|

|3|3|3|

|3|4|4|

+-----+-----+------+

9 rows in set (0.00 sec)

通过上述实验可以看出,在对组合索引id1和id2插入数据时,自动生成的结合列基于组合索引第一列d2进行排序,并按照递增顺序排列。

全部评论 (0)

还没有任何评论哟~