修復建立名稱為“index”的表列時出現的 MySQL 語法錯誤?


你不能將 index 用作列名,因為它是保留字。為此,你需要在列名周圍使用反引號。

如果你將保留字用作列名,你可能會看到以下錯誤 −

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; check the manual that corresponds to your 
MySQL server version for the right syntax to use near 'int )ENGINE=MyISAM' at line 4

我們首先建立一個表。在此,我們將一個保留字 index 用作列名,但在反引號中包含它不會產生錯誤 −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> `index` int
   -> )ENGINE=MyISAM;
Query OK, 0 rows affected (0.28 sec)

使用 insert 命令在表中插入一些記錄 −

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)

使用 select 語句從此表顯示所有記錄 −

mysql> select *from DemoTable;

這將產生以下輸出 −

+----+-------+
| Id | index |
+----+-------+
|  1 |     4 |
|  2 |     8 |
|  3 |    12 |
+----+-------+
3 rows in set (0.00 sec)

更新於: 12-Dec-2019

732 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.