保留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 -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> START TRANSACTION; mysql> insert into reservingAutoIncrementDemo values(),(),(),(); Records: 4 Duplicates: 0 Warnings: 0 mysql> select *from reservingAutoIncrementDemo; +--------+ | UserId | +--------+ | 1 | | 2 | | 3 | | 4 | +--------+ 4 rows in set (0.00 sec) mysql> rollback;
这是保留MySQLauto_incrementedID的查询-
mysql> SELECT LAST_INSERT_ID() INTO @IncrementedValue;
让我们检查保留的auto_incremented值。查询如下-
mysql> select @IncrementedValue;
这是输出-
+-------------------+ | @IncrementedValue | +-------------------+ | 1 | +-------------------+ 1 row in set (0.00 sec)