如何插入 MySQL 中带有自动递增主键的数据?


无论何时,如果你的列具有自动递增的主键,那么有一个好处是你不必在 INSERT 命令中为此列提供值。这意味着 MySQL 将为该列提供值。

要理解上述概念,让我们先创建一个表。创建表的查询如下 −

mysql> create table AutoIncrementedPrimary
   -> (
   -> Id int auto_increment,
   -> Name varchar(100),
   -> Age int,
   -> Primary key(Id)
   -> );
Query OK, 0 rows affected (0.56 sec)

现在仅插入 Name 和 Age 列的记录,由于 Id 列被设置为自动增量,因此 MySQL 将自行提供 Id 列的值。插入记录的查询如下 −

mysql> insert into AutoIncrementedPrimary(Name,Age) values('John',23);
Query OK, 1 row affected (0.12 sec)

mysql> insert into AutoIncrementedPrimary(Name,Age) values('Sam',24);
Query OK, 1 row affected (0.15 sec)

mysql> insert into AutoIncrementedPrimary(Name,Age) values('Carol',30);
Query OK, 1 row affected (0.13 sec)

mysql> insert into AutoIncrementedPrimary(Name,Age) values('Johnson',28);
Query OK, 1 row affected (0.16 sec)

现在,我们使用 select 命令显示表中的所有记录。查询如下 −

mysql> select *from AutoIncrementedPrimary;

输出

+----+---------+------+
| Id | Name    | Age  |
+----+---------+------+
|  1 | John    |   23 |
|  2 | Sam     |   24 |
|  3 | Carol   |   30 |
|  4 | Johnson |   28 |
+----+---------+------+
4 rows in set (0.00 sec)

查看上述示例输出,Id 列的值是由 MySQL 提供的。

更新日期:30-7-2019

3 千 + 浏览

开启你的 职业生涯

完成课程以获得认证

开始吧
广告
© . All rights reserved.