如何将SQL中的主键更改为自动增量?

发布于 2024-08-30 20:10:13 字数 780 浏览 2 评论 0原文

我在 MySQL 中有一个表,它有一个主键:

mysql> desc gifts;
+---------------+-------------+------+-----+---------+-------+
| Field         | Type        | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| giftID        | int(11)     | NO   | PRI | NULL    |       |
| name          | varchar(80) | YES  |     | NULL    |       |
| filename      | varchar(80) | YES  |     | NULL    |       |
| effectiveTime | datetime    | YES  |     | NULL    |       |
+---------------+-------------+------+-----+---------+-------+

但我想让它自动增量。

以下语句失败。如何修改才能使其正常工作?谢谢

mysql> alter table gifts modify giftID int primary key auto_increment;
ERROR 1068 (42000): Multiple primary key defined

I have a table in MySQL that has a primary key:

mysql> desc gifts;
+---------------+-------------+------+-----+---------+-------+
| Field         | Type        | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| giftID        | int(11)     | NO   | PRI | NULL    |       |
| name          | varchar(80) | YES  |     | NULL    |       |
| filename      | varchar(80) | YES  |     | NULL    |       |
| effectiveTime | datetime    | YES  |     | NULL    |       |
+---------------+-------------+------+-----+---------+-------+

but I wanted to make it auto_increment.

The following statement failed. How can it be modified so that it can work? thanks

mysql> alter table gifts modify giftID int primary key auto_increment;
ERROR 1068 (42000): Multiple primary key defined

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

野侃 2024-09-06 20:10:13

忽略主键属性:

ALTER TABLE gifts MODIFY giftID INT AUTO_INCREMENT;

某些列属性(例如PRIMARY KEY)并不完全是列的属性,而是其他事物的快捷方式。例如,标记为 PRIMARY KEY 的列放置在 PRIMARY 索引中。此外,PRIMARY 索引中的所有列都被赋予了 NOT NULL 属性。 (旁白:要拥有多列主键,您必须使用单独的约束子句,而不是多个 PRIMARY KEY 列属性。)由于该列已经在 PRIMARY 中索引,修改列时无需再次指定。尝试使用 SHOW CREATE TABLEgift; 查看使用 PRIMARY KEY 属性的影响。

Leave off the primary key attribute:

ALTER TABLE gifts MODIFY giftID INT AUTO_INCREMENT;

Certain column attributes, such as PRIMARY KEY, aren't exactly properties of the column so much as shortcuts for other things. A column marked PRIMARY KEY, for example, is placed in the PRIMARY index. Futhermore, all columns in the PRIMARY index are given the NOT NULL attribute. (Aside: to have a multi-column primary key, you must use a separate constraint clause rather than multiple PRIMARY KEY column attributes.) Since the column is already in the PRIMARY index, you don't need to specify it again when you modify the column. Try SHOW CREATE TABLE gifts; to see the affects of using the PRIMARY KEY attribute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文