我们如何将 AUTO_INCREMENT 应用于列?

mysqlmysqli database

AUTO_INCREMENT 表示该列将自动获取值。为了说明这一点,我们创建了一个表"employees",如下所示 −

mysql> Show Create Table employees\G

*************************** 1. row ***************************
Table: employees

Create Table: CREATE TABLE `employees` (
   `Id` int(11) NOT NULL AUTO_INCREMENT,
   `Name` varchar(35) DEFAULT NULL,
   PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

1 row in set (0.00 sec)

从上面的结果集中,我们可以看到列 id 被赋予了自动增加选项。现在,当我们在 Name 字段中插入值时,id 字段将自动获取值 −

mysql> Insert Into employees(Name) Values('Ram');
Query OK, 1 row affected (0.09 sec)

mysql> Insert Into employees(Name) Values('Shyam');
Query OK, 1 row affected (0.03 sec)

mysql> Insert Into employees(Name) Values('Mohan');
Query OK, 1 row affected (0.04 sec)

mysql> Insert Into employees(Name) Values('Sohan');
Query OK, 1 row affected (0.04 sec)

mysql> Select * from employees;

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Ram   |
| 2  | Shyam |
| 3  | Mohan |
| 4  | Sohan |
+----+-------+

4 rows in set (0.00 sec)

相关文章