是否强制为主键设置 AUTO_INCREMENT 值?


是的,将 AUTO_INCREMENT 与 PRIMARY KEY 一起使用。我们首先创建一个表−

mysql> create table DemoTable
(
   EmployeeId int NOT NULL AUTO_INCREMENT,
   EmployeeName varchar(40),
   EmployeeAge int,
   PRIMARY KEY(EmployeeId),
   UNIQUE KEY(EmployeeName,EmployeeAge)
);
Query OK, 0 rows affected (0.96 sec)

我们来检查表的表描述−

mysql> desc DemoTable;

这将产生以下输出−

+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| EmployeeId   | int(11)     | NO   | PRI | NULL    | auto_increment |
| EmployeeName | varchar(40) | YES  | MUL | NULL    |                |
| EmployeeAge  | int(11)     | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
3 rows in set (0.17 sec)

使用 INSERT 命令在表中插入一些记录−

mysql> insert into DemoTable(EmployeeName,EmployeeAge) values('Chris',25);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(EmployeeName,EmployeeAge) values('Robert',34);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(EmployeeName,EmployeeAge) values('Mike',32);
Query OK, 1 row affected (0.09 sec)

使用 SELECT 语句显示表中的所有记录−

mysql> select *from DemoTable;

这将产生以下输出−

+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
|          1 | Chris        |          25 |
|          3 | Mike         |          32 |
|          2 | Robert       |          34 |
+------------+--------------+-------------+
3 rows in set (0.00 sec)

更新于: 04 十月 2019

149 次浏览

开启你的职业生涯

完成课程获得认证

开始
广告