(1)测试表,有主键
create table test_pri_1(
age int primary key,
name varchar(20)
);
alter table test_pri_1 add column id int;
show create table test_pri_1\G
mysql> show create table test_pri_1\G
*************************** 1. row ***************************
Table: test_pri_1
Create Table: CREATE TABLE `test_pri_1` (
`age` int(11) NOT NULL,
`name` varchar(20) DEFAULT NULL,
`id` int(11) DEFAULT NULL,
PRIMARY KEY (`age`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
添加一列设置自动增长列:
alter table test_pri_1 modify id int auto_increment;
mysql> alter table test_pri_1 modify id int auto_increment;
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
alter table test_pri_1 modify age int auto_increment;
*************************** 1. row ***************************
Table: test_pri_1
Create Table: CREATE TABLE `test_pri_1` (
`age` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`id` int(11) DEFAULT NULL,
PRIMARY KEY (`age`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.01 sec)
(2)测试表,有索引
create table test_pri_2(
age int,
name varchar(20),
index ind_name(age)
);
--设置一个字段为自增长列
alter table test_pri_2 modify age int auto_increment;
--添加另一个字段id
alter table test_pri_2 add column id int;
mysql> alter table test_pri_2 add column id int;
Query OK, 0 rows affected (0.29 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> show create table test_pri_2\G
*************************** 1. row ***************************
Table: test_pri_2
Create Table: CREATE TABLE `test_pri_2` (
`age` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`id` int(11) DEFAULT NULL,
KEY `ind_name` (`age`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
将添加的字段id设置为自增长列:
alter table test_pri_2 modify id int auto_increment;
mysql> alter table test_pri_2 modify id int auto_increment;
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
添加一个主键字段,并修改主键字段为自增长列:
--添加一个主键字段
alter table test_pri_2 add column id1 int;
alter table test_pri_2 add primary key(id1);
--修改主键字段为自增长列出错
alter table test_pri_2 modify id1 int auto_increment;
mysql> show create table test_pri_2\G
*************************** 1. row ***************************
Table: test_pri_2
Create Table: CREATE TABLE `test_pri_2` (
`age` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`id` int(11) DEFAULT NULL,
`id1` int(11) NOT NULL,
PRIMARY KEY (`id1`),
KEY `ind_name` (`age`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
mysql> alter table test_pri_2 modify id1 int auto_increment;
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
综上,mysql的自增长列auto_increment有如下特性:
(1)一个表中只有一个字段能被设置为自动增长,并且这个字段必须定义为key(或者索引);
(2)mysql默认认为自动增长的键字段为主键字段,所以,结合着一个表中只有一个主键的定义,auto_increment往往只针对于主键字段进行设置,因为一个表中如果已经存在主键,当我们对非主键的字段定义auto_increment时会报错。