Nguyên nhân lỗi
Khi định nghĩa cột AUTO_INCREMENT, MySQL yêu cầu cột đó phải là khóa chính (PRIMARY KEY) hoặc khóa duy nhất (UNIQUE KEY). Nếu không, sẽ báo lỗi 1075.
1. Ví dụ gây lỗi
mysql> create table DemoTable (
StudentId int NOT NULL AUTO_INCREMENT,
StudentName varchar(40),
StudentAge int
);
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
2. Cách sửa: thêm PRIMARY KEY
mysql> create table DemoTable (
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName varchar(40),
StudentAge int
);
Query OK, 0 rows affected (1.01 sec)
3. Chèn và kiểm tra
mysql> insert into DemoTable(StudentName,StudentAge) values('Chris Brown',19);
mysql> insert into DemoTable(StudentName,StudentAge) values('David Miller',18);
mysql> insert into DemoTable(StudentName,StudentAge) values('John Doe',20);
mysql> select * from DemoTable;
+-----------+--------------+------------+ | StudentId | StudentName | StudentAge | +-----------+--------------+------------+ | 1 | Chris Brown | 19 | | 2 | David Miller | 18 | | 3 | John Doe | 20 | +-----------+--------------+------------+ 3 rows in set (0.00 sec)
Tóm tắt: Cột AUTO_INCREMENT bắt buộc phải là khóa chính hoặc khóa duy nhất.