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

การแก้ไข MySQL ERROR 1075: Incorrect table definition

ข้อผิดพลาด ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key เกิดขึ้นเมื่อสร้างตารางที่มีคอลัมน์ AUTO_INCREMENT แต่ไม่ได้กำหนดเป็น PRIMARY KEY

ตัวอย่างที่ทำให้เกิด Error

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

วิธีแก้ไข: เพิ่ม 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)

เพิ่มข้อมูลทดสอบ

mysql> insert into DemoTable(StudentName,StudentAge) values('Chris Brown',19); Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable(StudentName,StudentAge) values('David Miller',18); Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentName,StudentAge) values('John Doe',20); Query OK, 1 row affected (0.11 sec)

แสดงข้อมูล

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)

สรุปกฎสำคัญ

  • คอลัมน์ที่มี AUTO_INCREMENT ต้องเป็น PRIMARY KEY หรือ UNIQUE KEY
  • ตารางหนึ่งมีคอลัมน์ AUTO_INCREMENT ได้เพียงคอลัมน์เดียว
  • คอลัมน์ AUTO_INCREMENT ต้องเป็นชนิดข้อมูลตัวเลข (INT, BIGINT, ฯลฯ)