gpt4 book ai didi

MySQL 自动 ID 列

转载 作者:行者123 更新时间:2023-11-29 06:16:59 25 4
gpt4 key购买 nike

我想知道如何让 MySQL 自动拥有一个列,该列将每行加 1(第 1 行的 ID 为 1,第 2 行的 ID 为 2,等等)例如:
每次新用户在网站上注册时,都会为他们分配一个 ID 号。从 1 开始,然后是 2,等等。

ID|用户名|密码
1 |鲍勃 |drowssaP
2 |吉尔 |猫

最佳答案

试试 AUTO_INCREMENT。 Documentation here

如果你在你的表创建声明中添加那个神奇的词:),它会为你施展魔法:)

mysql> CREATE TABLE Users (
-> ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Username varchar(255) NOT NULL,
-> Password varchar(255) NOT NULL
-> );
Query OK, 0 rows affected (0.52 sec)

mysql> INSERT INTO Users(Username, Password) VALUES('vladimir', 'ilich_lenin');
Query OK, 1 row affected (0.12 sec)

mysql> INSERT INTO Users(Username, Password) VALUES('friedrich', 'engels');
Query OK, 1 row affected (0.04 sec)

mysql> SELECT * FROM Users;
+----+-----------+-------------+
| ID | Username | Password |
+----+-----------+-------------+
| 1 | vladimir | ilich_lenin |
| 2 | friedrich | engels |
+----+-----------+-------------+
2 rows in set (0.02 sec)

编辑

mysql> CREATE TABLE Persons ( ID int NOT NULL PRIMARY KEY, Username varchar(255) NOT NULL, Password varchar(255) NOT NULL);
Query OK, 0 rows affected (0.25 sec)

mysql> SHOW CREATE TABLE

CREATE TABLE `Persons` (
`ID` int(11) NOT NULL,
`Username` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

1 row in set (0.00 sec)

mysql> ALTER TABLE Persons MODIFY ID INTEGER NOT NULL AUTO_INCREMENT;
Query OK, 0 rows affected (0.50 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> SHOW CREATE TABLE Persons;
CREATE TABLE `Persons` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Username` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

1 row in set (0.00 sec)

mysql> INSERT INTO Persons(Username, Password) VALUES('friedrich', 'engels');
Query OK, 1 row affected (0.06 sec)

mysql> INSERT INTO Persons(Username, Password) VALUES('karl', 'marx');
Query OK, 1 row affected (0.08 sec)

mysql> SELECT * FROM Persons
-> ;
+----+-----------+----------+
| ID | Username | Password |
+----+-----------+----------+
| 1 | friedrich | engels |
| 2 | karl | marx |
+----+-----------+----------+
2 rows in set (0.00 sec)

关于MySQL 自动 ID 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35326718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com