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

การทำงานกับ AUTO_INCREMENT Columns ใน MySQL

ทำงานกับ AUTO_INCREMENT columns ใน MySQL

AUTO_INCREMENT attribute generate unique identifier สำหรับ new rows ตัวอย่าง:

Query

CREATE TABLE tableName (
    id MEDIUMINT NOT NULL AUTO_INCREMENT,
    name CHAR(30) NOT NULL,
    PRIMARY KEY (id)
);
INSERT INTO tableName (name) VALUES ('val1'),('val2'),('val3'),('val4');
SELECT * FROM tableName;

Output

+----+---------+
| id | name    |
+----+---------+
| 1  | val1    |
| 2  | val2    |
| 3  | val3    |
| 4  | val4    |
+----+---------+

ไม่ระบุค่า AUTO_INCREMENT column → MySQL assign sequence อัตโนมัติ ใส่ 0 เริ่มจาก 0 ได้ (ถ้า NO_AUTO_VALUE_ON_ZERO SQL mode ไม่ enabled)

Column 'NOT NULL' → assign NULL ได้เพื่อ generate sequence

Insert value ลง AUTO_INCREMENT column → set value, reset sequence จาก largest value

Update existing AUTO_INCREMENT column → reset sequence

Recent value: LAST_INSERT_ID() (SQL) หรือ mysql_insert_id() (C API)

Rules:

  • 1 AUTO_INCREMENT column ต่อ table (typically integer)
  • ต้อง indexed (PRIMARY KEY หรือ UNIQUE)
  • ต้อง NOT NULL constraint
  • Set attribute → MySQL auto-add NOT NULL