`

mysql中的反引号与保留关键字desc问题

阅读更多
键盘上1左边,Esc下边那个键就是反引号键
mysql中,desc是保留字,建表时不能用于字段名,表名:
mysql>  create table desc (id varchar(255));
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 'desc (id varchar(255))' at line 1
mysql>  create table test3(desc varchar(255));
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 'desc varchar(255))' at line 1
但将desc放到反引号中则正常
mysql>  create table `desc` (id varchar(255));
Query OK, 0 rows affected (0.01 sec)
mysql>  create table test3 (`desc` varchar(255));
Query OK, 0 rows affected (0.00 sec)
mysql> drop table desc;
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 'desc' at line 1
mysql> drop table `desc`;
Query OK, 0 rows affected (0.00 sec)
有些管理员在建表时,为了省事,可能会选择从一个现有的表cp建表语句,修改创建.字段命名如果不规范的话,可能会用到mysql中的保留字,如上述的desc
例如从show create table xxx 或者mysqldump --no-data中取出建表语句,形式如下:
CREATE TABLE `test` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `time` datetime NOT NULL default '0000-00-00 00:00:00',
  `type` int(10) unsigned NOT NULL default '0',
  `desc` varchar(255) default NULL,
  primary key `i_id` (`id`)
) ENGINE=innodb DEFAULT CHARSET=latin1;
创建成功后,在insert时如果不带反引号就会遇到问题
mysql> insert into test(`time`,`type`,`desc`) values(now(),5,'aa');
Query OK, 1 row affected (0.01 sec)
mysql> insert into test(time,type,desc) values(now(),5,'aa');
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 'desc) values(now(),5,'aa')' at line 1
mysql>
针对这个问题,有2个建议
1) 在建表时,不要用保留字作表名,字段名.可以加一个前缀标志加以区分,如在表名前加t_, 在列名前加F
2) 建表时,不要给表名/字段名/索引名加反引号,以免隐藏问题
反引号中带保留字建表时,mysql为什么不报错呢?
得先搞清楚反引号的本意,及show create table,mysqldump出来的数据带反引号的目的是什么.
有哪位知道,望不吝踢教~.~

相关资料:

mysql中的反引号与保留关键字desc问题来源网络,如有侵权请告知,即处理!

 

本文来源于:http://biancheng.dnbcw.info/mysql/267499.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics