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

ตั้งค่า AUTO_INCREMENT เริ่มต้นขณะสร้างตารางใน MySQL

บทนำ

สามารถกำหนดค่าเริ่มต้นของ AUTO_INCREMENT ได้ทันทีขณะสร้างตาราง โดยใช้ clause AUTO_INCREMENT = value ที่ท้ายคำสั่ง CREATE TABLE

ตัวอย่างการสร้างตารางพร้อมตั้งค่า AUTO_INCREMENT = 30

mysql> CREATE TABLE DemoTable (
    -> StudentId INT NOT NULL AUTO_INCREMENT,
    -> StudentFirstName VARCHAR(100),
    -> StudentLastName VARCHAR(100),
    -> StudentAge INT,
    -> StudentCountryName VARCHAR(100),
    -> PRIMARY KEY(StudentId)
    -> ) AUTO_INCREMENT = 30;
Query OK, 0 rows affected (0.69 sec)

เพิ่มข้อมูลทดสอบ

mysql> INSERT INTO DemoTable(StudentFirstName, StudentLastName, StudentAge, StudentCountryName)
    -> VALUES('John', 'Smith', 21, 'US');
mysql> INSERT INTO DemoTable(StudentFirstName, StudentLastName, StudentAge, StudentCountryName)
    -> VALUES('Chris', 'Brown', 20, 'AUS');

แสดงข้อมูล

mysql> SELECT * FROM DemoTable;

ผลลัพธ์

+-----------+------------------+-----------------+------------+--------------------+
| StudentId | StudentFirstName | StudentLastName | StudentAge | StudentCountryName |
+-----------+------------------+-----------------+------------+--------------------+
| 30        | John             | Smith           | 21         | US                 |
| 31        | Chris            | Brown           | 20         | AUS                |
+-----------+------------------+-----------------+------------+--------------------+
2 rows in set (0.00 sec)

คำอธิบาย

  • แถวแรกได้ Id = 30 (ค่าที่ตั้งไว้)
  • แถวถัดไปจะเพิ่มขึ้นทีละ 1 ตามปกติ
  • วิธีนี้เหมาะสำหรับการรวมข้อมูลจากหลายระบบ (Data Migration) เพื่อไม่ให้ ID ซ้ำกัน