SQL创建表用order字段报错,改为orders正常的原因咨询
问题描述
我是SQL新手,正在跟随YouTube上networkchunk的教程学习。遇到如下问题:
- 创建表时第一个字段设为
order会出现报错 - 创建同一张表时第一个字段设为
orders则无报错
执行的SQL命令及报错信息:
mysql> show tables -> ; +---------------------+ | Tables_in_nc_coffee | +---------------------+ | coffee_table | | orders_table | +---------------------+ 2 rows in set (0.00 sec) mysql> drop table orders_table; Query OK, 0 rows affected (0.03 sec) mysql> show tables -> ; +---------------------+ | Tables_in_nc_coffee | +---------------------+ | coffee_table | +---------------------+ 1 row in set (0.00 sec) mysql> create table orders_table ( -> order int, -> coffee int, -> customer int -> ); 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 'order int, coffee int, customer int )' at line 2 mysql> create table orders_table ( order int, coffee int, customer int ); 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 'order int, coffee int, customer int )' at line 1 mysql> create table orders_table ( orders int, coffee int, customer int ); Query OK, 0 rows affected (0.03 sec) mysql>
原因分析
order是MySQL的保留关键字,这类关键字被数据库系统预留用于特定语法(比如ORDER BY排序语句),不能直接用作表名、字段名等标识符,否则会触发语法解析错误。
而orders只是普通字符串,不属于保留关键字范畴,所以可以正常作为字段名使用。
解决办法(如果非要用order作为字段名):
用MySQL的反引号(`)将字段名包裹,让数据库将其识别为普通标识符而非关键字,示例:
create table orders_table ( `order` int, coffee int, customer int );
内容的提问来源于stack exchange,提问作者Sahil Gautam
相关产品推荐
相关产品推荐

