Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

หาค่า Seed (ค่าเริ่มต้น) ของ AUTO_INCREMENT ใน MySQL

ใช้ SHOW VARIABLES LIKE 'auto_inc%' ดูค่า Global หรือ information_schema.tables ดูค่าตารางเฉพาะ

1. ดูค่า Global Settings

mysql> SHOW VARIABLES LIKE 'auto_inc%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 1     |
| auto_increment_offset    | 1     |
+--------------------------+-------+
  • auto_increment_increment - ก้าวกระโดด (Default 1)
  • auto_increment_offset - ค่าเริ่มต้น (Default 1)

2. ดูค่า AUTO_INCREMENT ของตารางเฉพาะ

SELECT AUTO_INCREMENT FROM information_schema.tables 
WHERE table_schema = 'your_db' AND table_name = 'your_table';

3. ตัวอย่างควบคุม AUTO_INCREMENT

สร้างตารางและแทรกข้อมูล

mysql> CREATE TABLE DemoTable (StudentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
mysql> INSERT INTO DemoTable VALUES (), ();  -- ได้ 1, 2

เปลี่ยนค่าเริ่มต้นถัดไปเป็น 1000

mysql> ALTER TABLE DemoTable AUTO_INCREMENT = 1000;
mysql> INSERT INTO DemoTable VALUES (), ();  -- ได้ 1000, 1001

ผลลัพธ์

+-----------+
| StudentId |
+-----------+
| 1         |
| 2         |
| 1000      |
| 1001      |
+-----------+

ข้อควรระวัง

  • AUTO_INCREMENT ต้องเป็น Primary Key หรือ Unique Key
  • ไม่สามารถตั้งค่าต่ำกว่าค่าสูงสุดที่มีอยู่ได้
  • InnoDB: ค่า Auto Increment ไม่ Persistent หลัง Restart (MySQL < 8.0) → ใช้ innodb_autoinc_lock_mode
  • MySQL 8.0+ รองรับ Persistent Auto Increment