MySQL Automatic ID column

后端 未结 1 519
失恋的感觉
失恋的感觉 2021-01-25 09:47

I was wondering how to make MySQL automatically have a column that adds 1 to every row that is made (Row 1 will have ID 1, Row 2 will get ID 2, etc.) For example:
Every time

相关标签:
1条回答
  • 2021-01-25 10:16

    Try AUTO_INCREMENT. Documentation here

    If you add, that magic word :) to your table creation declaration, it will do the magic for you :)

    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)
    

    EDIT

    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)
    
    0 讨论(0)
提交回复
热议问题