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

Lấy giá trị AUTO_INCREMENT tiếp theo (next primary key) mà không cần INSERT trong MySQL

Tạo bảng có AUTO_INCREMENT

mysql> CREATE TABLE DemoTable1399 (
    -> StudentId INT NOT NULL AUTO_INCREMENT,
    -> PRIMARY KEY(StudentId)
    -> );
Query OK, 0 rows affected (0.53 sec)
mysql> INSERT INTO DemoTable1399 VALUES(),(),();

Dữ liệu hiện có

mysql> SELECT * FROM DemoTable1399;
+-----------+
| StudentId |
+-----------+
| 1         |
| 2         |
| 3         |
+-----------+

Truy vấn information_schema để lấy next AUTO_INCREMENT

mysql> SELECT AUTO_INCREMENT AS NextPrimaryKey
    -> FROM information_schema.tables
    -> WHERE table_schema = DATABASE()
    ->   AND table_name = 'DemoTable1399';

Kết quả: 4

+----------------+
| NextPrimaryKey |
+----------------+
| 4              |
+----------------+

Lưu ý: Giá trị này có thể thay đổi nếu có INSERT/DELETE/ROLLBACK. Không nên dùng để dự đoán ID trong ứng dụng đa luồng (race condition).