MySQL自动ID栏 [英] MySQL Automatic ID column

查看:51
本文介绍了MySQL自动ID栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使MySQL自动具有在创建的每一行中加1的列(行1的ID为1,行2的ID为2,依此类推). 例如:
每次新用户在网站上注册时,都会为其分配一个ID号.从1开始,然后从2开始,等等.

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 a new user signs up on a website, they are assigned an ID number. Starting at 1, then 2, etc.

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

ID|Username|Password
1 |Bob |drowssaP
2 |Jill |cats

推荐答案

尝试使用AUTO_INCREMENT. 此处的文档

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)

编辑

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栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆