การใช้ ALTER TABLE เปลี่ยนค่า Auto Increment ถัดไป
คำสั่ง ALTER TABLE ... AUTO_INCREMENT = value กำหนดค่า ID ถัดไปที่จะถูกสร้าง
รูปแบบคำสั่ง
ALTER TABLE yourTableName AUTO_INCREMENT = IntegerValue;
ตัวอย่าง: สร้างตารางและดูค่าเริ่มต้น
mysql> CREATE TABLE changeCurrentAutoIncrementValue (
-> CurrentCount INT AUTO_INCREMENT,
-> PRIMARY KEY(CurrentCount)
-> );
Query OK, 0 rows affected (0.60 sec)
mysql> INSERT INTO changeCurrentAutoIncrementValue VALUES();
mysql> INSERT INTO changeCurrentAutoIncrementValue VALUES();
mysql> INSERT INTO changeCurrentAutoIncrementValue VALUES();
mysql> INSERT INTO changeCurrentAutoIncrementValue VALUES();
mysql> SELECT * FROM changeCurrentAutoIncrementValue;
+--------------+ | CurrentCount | +--------------+ | 1 | | 2 | | 3 | | 4 | +--------------+ 4 rows in set (0.00 sec)
เปลี่ยน Auto Increment เริ่มที่ 300
mysql> ALTER TABLE changeCurrentAutoIncrementValue AUTO_INCREMENT = 300; Query OK, 0 rows affected (0.27 sec)
Insert ใหม่ จะเริ่มจาก 300
mysql> INSERT INTO changeCurrentAutoIncrementValue VALUES(); mysql> INSERT INTO changeCurrentAutoIncrementValue VALUES(); mysql> INSERT INTO changeCurrentAutoIncrementValue VALUES(); mysql> SELECT * FROM changeCurrentAutoIncrementValue;
+--------------+ | CurrentCount | +--------------+ | 1 | | 2 | | 3 | | 4 | | 300 | | 301 | | 302 | +--------------+ 7 rows in set (0.00 sec)
ข้อควรระวัง:
- ค่าใหม่ต้อง มากกว่า ค่าสูงสุดที่มีอยู่แล้ว (MAX(id))
- ไม่สามารถตั้งค่าต่ำกว่าค่าที่มีอยู่ได้ (จะ error หรือถูกปรับเป็น MAX+1)
- ไม่กระทบข้อมูลที่มีอยู่แล้ว แค่กำหนดค่าถัดไป
- ใช้ได้กับ AUTO_INCREMENT column เท่านั้น
การใช้งานจริง: รีเซ็ตหลังลบข้อมูลทิ้งมาก, merge ข้อมูลจากระบบอื่น, reserve ID range