MySQL自动ID列

时间:2016-02-10 21:54:33

标签: mysql

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

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

1 个答案:

答案 0 :(得分:1)

尝试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)