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

วิธีแทรกค่าเองเข้าไปในคอลัมน์ AUTO_INCREMENT ใน MySQL

คุณสามารถทำได้โดยใช้คำสั่ง INSERT ปกติ โดยระบุค่าสำหรับคอลัมน์ AUTO_INCREMENT ไวยากรณ์มีดังนี้:

INSERT INTO yourTableName (yourIdColumnName, yourColumnName) values(value1, 'value2');

มาสร้างตารางก่อน:

mysql> create table InsertValueInAutoIncrement ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserName varchar(20) ); Query OK, 0 rows affected (0.59 sec)

แทรกข้อมูล โดยเราก็แทรกค่าเองสำหรับฟิลด์ UserId ที่เป็น AUTO_INCREMENT:

mysql> insert into InsertValueInAutoIncrement(UserName) values('John'); Query OK, 1 row affected (0.19 sec) mysql> insert into InsertValueInAutoIncrement(UserName) values('Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into InsertValueInAutoIncrement(UserName) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into InsertValueInAutoIncrement(UserName) values('Bob'); Query OK, 1 row affected (0.18 sec) mysql> insert into InsertValueInAutoIncrement(UserId,UserName) values(100,'Maxwell'); Query OK, 1 row affected (0.18 sec) mysql> insert into InsertValueInAutoIncrement(UserName) values('James'); Query OK, 1 row affected (0.20 sec) mysql> insert into InsertValueInAutoIncrement(UserId,UserName) values(1000,'Larry'); Query OK, 1 row affected (0.12 sec)

แสดงข้อมูลทั้งหมด:

mysql> select * from InsertValueInAutoIncrement;

ตารางจะเป็นดังนี้:

+--------+----------+ | UserId | UserName | +--------+----------+ | 1 | John | | 2 | Carol | | 3 | Sam | | 4 | Bob | | 100 | Maxwell | | 101 | James | | 1000 | Larry | +--------+----------+ 7 rows in set (0.00 sec)

สังเกตว่าหลังจากแทรก UserId=100 ค่า AUTO_INCREMENT ถัดไปจะกลายเป็น 101 และหลังจากแทรก 1000 ถัดไปจะเป็น 1001