MySQL, safely using reserved word in query [duplicate]

此生再无相见时 提交于 2019-11-28 06:27:25

问题


This question already has an answer here:

  • Syntax error due to using a reserved word as a table or column name in MySQL 1 answer

I need to return a multidimensional array from a query with the id keys named key. (needed for object keys in amazon S3 API)

example:

Array ( [0] => Array ( [key] => 8 ) [1] => Array ( [key] => 7 ) [2] => Array ( [key] => 6 ) )

The problem: key is a reserved name in MySQL. I have to use the name key.

The following query gives an error

SELECT `file_name` AS key FROM (`uploads`)

but adding backticks around key doesn't give errors

SELECT `file_name` AS `key` FROM (`uploads`)

Is it safe to continue like this or is there a better way? I was thinking to rename the id key in the array in PHP but doing it in the query seems faster


回答1:


As stated, use backticks.

From the MYSQL Docs

Reserved words are permitted as identifiers if you quote them as described in Section 9.2, “Schema Object Names”:

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax ...
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT);
Query OK, 0 rows affected (0.01 sec)



回答2:


To be away from reserved keyword around table field in query always considered as the best way...If you are using in reserved keyword in query, then backtick allow you to use reserved keyword...

As backtick is not defined in ANSI SQL standard, it'll probably create problem when you migrate from MySQL environment...



来源:https://stackoverflow.com/questions/12546267/mysql-safely-using-reserved-word-in-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!