ทำความเข้าใจ AUTO_INCREMENT behavior
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 → MySQL assign sequence อัตโนมัติ ใส่ 0 เริ่มจาก 0 ได้ (ถ้า NO_AUTO_VALUE_ON_ZERO disabled)
- 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) - connection-specific
- ใช้ smallest integer type ที่พอดี max sequence value
- Column ถึง upper range ของ data type → generate sequence fail
แนะนำ UNSIGNED attribute เพื่อ range มากขึ้นใน AUTO_INCREMENT column