การดึงค่า AUTO_INCREMENT ถัดไปจาก information_schema
สามารถดูค่า Primary Key ถัดไปที่จะถูกกำหนดได้โดยไม่ต้อง INSERT จริง ผ่าน information_schema.tables
สร้างตารางและเพิ่มข้อมูล 3 แถว
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();
mysql> insert into DemoTable1399 values();
mysql> insert into DemoTable1399 values();
ข้อมูลปัจจุบัน (ID 1, 2, 3)
+-----------+ | StudentId | +-----------+ | 1 | | 2 | | 3 | +-----------+
คำสั่งดู Next Auto Increment
mysql> select auto_increment as NextPrimaryKey
-> from information_schema.tables
-> where table_schema = database()
-> and table_name = 'DemoTable1399';
ผลลัพธ์
+----------------+ | NextPrimaryKey | +----------------+ | 4 | +----------------+
คอลัมน์สำคัญใน information_schema.tables
| คอลัมน์ | คำอธิบาย |
|---|---|
AUTO_INCREMENT | ค่าถัดไปที่จะมอบหมาย |
TABLE_SCHEMA | ชื่อ database |
TABLE_NAME | ชื่อตาราง |
ENGINE | Storage engine (InnoDB, MyISAM, etc.) |
TABLE_ROWS | ประมาณจำนวนแถว |
คำสั่งสั้นๆ (MySQL 5.7+)
SHOW TABLE STATUS LIKE 'DemoTable1399';
ดูคอลัมน์ Auto_increment ในผลลัพธ์
ข้อควรระวัง
- ค่า
AUTO_INCREMENTเพิ่มขึ้นเมื่อ INSERT สำเร็จ — หาก INSERT ล้มเหลว (duplicate key, constraint violation) อาจเพิ่มขึ้นไปแล้ว (gaps) TRUNCATE TABLEจะ reset AUTO_INCREMENT กลับเป็น 1 (หรือค่าเริ่มต้น)ALTER TABLE t AUTO_INCREMENT = 100— ตั้งค่าเริ่มต้นใหม่ (ต้อง > ค่าสูงสุดปัจจุบัน)- ใน Replication/Cluster ค่า AUTO_INCREMENT อาจไม่ต่อเนื่อง (ใช้ auto_increment_increment/offset)
กรณีใช้งาน: สร้าง ID ล่วงหน้าสำหรับ application logic, สร้าง reference number, debug sequence gaps