预留 MySQL 自动增量 ID?


要预留 MySQL 自动增量 ID,语法如下所示 −

START TRANSACTION;
insert into yourTableName values(),(),(),();
ROLLBACK;
SELECT LAST_INSERT_ID() INTO @anyVariableName;

为了理解上述语法,让我们创建一个表。创建表的查询如下 −

mysql> create table reservingAutoIncrementDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY
   -> );
Query OK, 0 rows affected (0.45 sec)

使用 insert 命令在表中插入一些记录。查询如下 −

mysql> START TRANSACTION;
Query OK, 0 rows affected (0.00 sec)
mysql> insert into reservingAutoIncrementDemo values(),(),(),();
Query OK, 4 rows affected (0.15 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select *from reservingAutoIncrementDemo;
+--------+
| UserId |
+--------+
| 1      |
| 2      |
| 3      |
| 4      |
+--------+
4 rows in set (0.00 sec)
mysql> rollback;
Query OK, 0 rows affected (0.00 sec)

以下是预留 MySQL auto_incremented ID 的查询 −

mysql> SELECT LAST_INSERT_ID() INTO @IncrementedValue;
Query OK, 1 row affected (0.00 sec)

让我们检查预留的自动增量值。查询如下所示 −

mysql> select @IncrementedValue;

以下是输出 −

+-------------------+
| @IncrementedValue |
+-------------------+
| 1                 |
+-------------------+
1 row in set (0.00 sec)

更新时间:30-Jul-2019

266 次浏览

开启你的 职业生涯

通过完成课程取得认证

开始学习
广告
© . All rights reserved.