Vấn đề
Từ index là từ khóa dành riêng (reserved word) trong MySQL. Đặt tên cột là index sẽ gây lỗi cú pháp:
mysql> create table DemoTable (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> index int
-> ) ENGINE=MyISAM;
ERROR 1064 (42000): You have an error in your SQL syntax...
near 'int )ENGINE=MyISAM' at line 4
Giải pháp: Sử dụng backtick (`)
Bao quanh tên cột bằng dấu backtick ` (phím cùng phím ~ trên bàn phím US) để MySQL hiểu đây là định danh (identifier), không phải từ khóa.
1. Tạo bảng đúng cú pháp
mysql> create table DemoTable (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> `index` int
-> ) ENGINE=MyISAM;
Query OK, 0 rows affected (0.28 sec)
2. Chèn và truy vấn dữ liệu
mysql> insert into DemoTable(`index`) values(4); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(`index`) values(8); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(`index`) values(12); Query OK, 1 row affected (0.06 sec) mysql> select *from DemoTable;
+----+-------+ | Id | index | +----+-------+ | 1 | 4 | | 2 | 8 | | 3 | 12 | +----+-------+ 3 rows in set (0.00 sec)
Các từ khóa thường gặp lỗi tương tự: order, group, select, where, key, primary, unique, check, references, table, database, user, password, ...
Quy tắc tốt: Luôn dùng backtick cho tên bảng, cột, index, alias trong SQL động hoặc code生成工具. Ví dụ: SELECT `id`, `name` FROM `user` WHERE `order` = 1