Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Dự trữ ID auto_increment trong MySQL?

Dự trữ (reserve) giá trị AUTO_INCREMENT trong MySQL

Sử dụng transaction: INSERT nhiều hàng rồi ROLLBACK để "nhảy" giá trị AUTO_INCREMENT, sau đó lấy LAST_INSERT_ID().

Cú pháp

START TRANSACTION;
INSERT INTO yourTableName VALUES (), (), (), ();
ROLLBACK;
SELECT LAST_INSERT_ID() INTO @variableName;

Ví dụ: Dự trữ 4 ID

Tạo bảng:

mysql> CREATE TABLE reservingAutoIncrementDemo (
    -> UserId INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    -> );

Thực hiện transaction:

mysql> START TRANSACTION;
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO reservingAutoIncrementDemo VALUES (), (), (), ();
Query OK, 4 rows affected (0.15 sec)

mysql> SELECT * FROM reservingAutoIncrementDemo;
+--------+
| UserId |
+--------+
| 1      |
| 2      |
| 3      |
| 4      |
+--------+

mysql> ROLLBACK;
Query OK, 0 rows affected (0.00 sec)

Lấy giá trị dự trữ:

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

mysql> SELECT @IncrementedValue;
+-------------------+
| @IncrementedValue |
+-------------------+
| 1                 |
+-------------------+

Giải thích

  • INSERT 4 hàng → AUTO_INCREMENT tăng lên 5
  • ROLLBACK xóa dữ liệu nhưng không reset AUTO_INCREMENT
  • LAST_INSERT_ID() trả về ID của hàng INSERT cuối cùng trong transaction (trước ROLLBACK)
  • Giá trị 1 ở đây là ID của hàng đầu tiên trong batch INSERT 4 hàng
  • INSERT tiếp theo sẽ bắt đầu từ 5

Ứng dụng thực tế

  • Dự trữ block ID cho hệ thống phân tán (sharding)
  • Tạo gap ý định cho mục đích business
  • Test logic xử lý ID không liên tiếp

Cách khác: ALTER TABLE AUTO_INCREMENT

ALTER TABLE yourTable AUTO_INCREMENT = 1000;

Đặt trực tiếp giá trị AUTO_INCREMENT tiếp theo (cần quyền ALTER).