简体   繁体   English

mysql:如何将列更改为PK Auto_Increment

[英]mysql: how to change column to be PK Auto_Increment

是否有一个单独的select语句可以完成所有这三个操作:主键,唯一键和auto_increment?

Here we create a little table: 这里我们创建一个小表:

mysql> CREATE TABLE test2 (id int);

Note Null is YES, and id is not a primary key, nor does it auto_increment. 注意Null是YES,并且id不是主键,也不是auto_increment。

mysql> DESCRIBE test2;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  |     | NULL    |       | 
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

Here is the alter command: 这是alter命令:

mysql> ALTER TABLE test2 MODIFY COLUMN id INT NOT NULL auto_increment, ADD primary key (id);

Now Null is NO, and id is a primary key with auto_increment. 现在Null为NO,并且id是具有auto_increment的主键。

mysql> describe test2;
describe test2;
+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| id    | int(11) | NO   | PRI | NULL    | auto_increment | 
+-------+---------+------+-----+---------+----------------+
1 row in set (0.00 sec)

Primary keys are always unique. 主键始终是唯一的。

主键始终是唯一的。

You cannot alter the database structure with DML (data manipulation language) statements like SELECT . 您无法使用SELECT类的DML (数据操作语言)语句来更改数据库结构。 You need DDL (data definition language) statements. 您需要DDL (数据定义语言)语句。 Table columns can be modified with ALTER TABLE : 可以使用ALTER TABLE修改表列:

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

The syntax is basically this: 语法基本上是这样的:

ALTER TABLE `foo`
CHANGE COLUMN `bar` `bar` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`foo`);

As about the exact changes you want to do, you must know that in relational databases a primary key is a value that serves to uniquely identify each row in a table. 关于要执行的确切更改,您必须知道在关系数据库中主键是一个用于唯一标识表中每一行的值。 It won't serve such purpose if it's not unique or NULL. 如果它不是唯一的或NULL,则将无法满足此目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM