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

การตั้งค่า Initial Value และ Auto Increment ใน MySQL

AUTO_INCREMENT attribute ใช้ generate unique identifier สำหรับ new rows หาก column declared 'NOT NULL' สามารถ assign NULL เพื่อ generate sequence ได้

Insert value ลง AUTO_INCREMENT column → column set to that value, sequence reset generate automatically จาก largest column value

Update existing AUTO_INCREMENT column → reset AUTO_INCREMENT sequence ด้วย

Recent auto-generated value: LAST_INSERT_ID() (SQL) หรือ mysql_insert_id() (C API) - connection-specific

ใช้ smallest integer data type ที่พอดี max sequence value ที่ต้องการ

Rules สำหรับ AUTO_INCREMENT

  • Table มีเพียง 1 AUTO_INCREMENT column (typically integer)
  • AUTO_INCREMENT column ต้อง indexed (PRIMARY KEY หรือ UNIQUE index)
  • AUTO_INCREMENT column ต้องมี NOT NULL constraint
  • Set AUTO_INCREMENT attribute → MySQL auto-add NOT NULL constraint

หาไม่มี id column ใช้:

ALTER TABLE tableName ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD INDEX (id);

หา id column มีอยู่แล้ว ใช้:

ALTER TABLE tableName AUTO_INCREMENT=specificValue;

'tableName' = table name, 'specificValue' = integer เริ่มต้น AUTO_INCREMENT values