(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時會報錯。