Yêu cầu
Cột StudentStartId không phải Primary Key nhưng có AUTO_INCREMENT bắt đầu từ 1000.
Giải pháp
MySQL cho phép AUTO_INCREMENT trên cột có INDEX (UNIQUE hoặc PRIMARY KEY).
Tạo bảng:
CREATE TABLE DemoTable639 (
StudentId INT PRIMARY KEY,
StudentStartId INT AUTO_INCREMENT,
StudentName VARCHAR(50),
INDEX (StudentStartId) -- BẮT BUỘC: index cho auto_increment column
);
Set giá trị bắt đầu:
ALTER TABLE DemoTable639 AUTO_INCREMENT = 1000;
Insert (chỉ đưa StudentId và StudentName):
INSERT INTO DemoTable639(StudentId, StudentName) VALUES
(1, 'John'), (2, 'Chris'), (3, 'Robert'), (4, 'David');
Kết quả:
+-----------+----------------+-------------+
| StudentId | StudentStartId | StudentName |
+-----------+----------------+-------------+
| 1 | 1000 | John |
| 2 | 1001 | Chris |
| 3 | 1002 | Robert |
| 4 | 1003 | David |
+-----------+----------------+-------------+
Quy tắc AUTO_INCREMENT trên non-PK
- Cột phải có INDEX (UNIQUE hoặc INDEX thường).
- Chỉ được 1 cột AUTO_INCREMENT mỗi bảng.
- Nếu bảng đã có PK auto_increment, cột khác KHÔNG thể auto_increment (trừ MySQL 8.0+ vớiGenerated column workaround).
Workaround MySQL 8.0: Generated Column
CREATE TABLE DemoTable639_v2 (
StudentId INT PRIMARY KEY AUTO_INCREMENT,
StudentName VARCHAR(50),
StudentStartId INT GENERATED ALWAYS AS (StudentId + 999) STORED
);
-- StudentStartId = StudentId + 999 → bắt đầu từ 1000
Lưu ý
ALTER TABLE ... AUTO_INCREMENT = Nchỉ tác động cho lần INSERT tiếp theo.- Giá trị N phải > max hiện tại của cột auto_increment.
- Không thể set AUTO_INCREMENT < giá trị max hiện tại.