MYSQL技巧:为现有字段添加自增属性
基本命令格式如下:
ALTER TABLE tbl_name MODIFY col_name column_definition
其中column_definition字段需要包括以下内容:
1、该列的数据类型及AUTO_INCREMENT字段;
2、如该列必须为NOT NULL及PRIMARY KEY(UNIQUE)属性。如果不是,需添加相应定义。
举个例子。已存在表test,结构如下:
mysql> desc test;
+----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | |
| username | varchar(15) | NO | | NULL | |
+----------+------------------+------+-----+---------+----------------+
先需要给主键列id添加AUTO_INCREMENT属性,只需执行以下指令即可:alter table test MODIFY id INT UNSIGNED AUTO_INCREMENT;
执行成功后,再查看表test的结构,即可看到auto_increment属性:
mysql> desc test;
+----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| username | varchar(15) | NO | | NULL | |
+----------+------------------+------+-----+---------+----------------+