如何将具有自动递增主键的数据插入到 MySQL?

mysqlmysqli database

只要您的列具有自动递增主键,那么就有一个优点,即您无需在 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 插入记录,MySQL 将自行提供 Id 列的值,因为它已设置为 auto_increment。插入记录的查询如下 −

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 提供。


相关文章