创建名为"index"的表列时修复 MySQL 语法错误?
mysqlmysqli database更新于 2024/2/4 3:03:00
您不能使用 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
首先让我们创建一个表。在这里,我们使用保留字索引作为列名,但用反引号括起来不会出错−
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)