MySQL,在查询中安全地使用保留字 [英] MySQL, safely using reserved word in query
问题描述
我需要使用ID为key
的ID键从查询返回多维数组. (在Amazon S3 API中需要对象键)
I need to return a multidimensional array from a query with the id keys named key
. (needed for object keys in amazon S3 API)
示例:
Array ( [0] => Array ( [key] => 8 ) [1] => Array ( [key] => 7 ) [2] => Array ( [key] => 6 ) )
问题:key
是MySQL中的保留名称.我拥有使用姓名键.
The problem: key
is a reserved name in MySQL. I have to use the name key.
以下查询给出了错误
SELECT `file_name` AS key FROM (`uploads`)
但是在key
周围添加反引号不会给出错误
but adding backticks around key
doesn't give errors
SELECT `file_name` AS `key` FROM (`uploads`)
像这样继续下去是否安全?是否有更好的方法?我当时想在PHP中重命名数组中的id键,但是在查询中这样做似乎更快
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
推荐答案
如上所述,请使用反引号.
As stated, use backticks.
从 MYSQL文档
如果您按照第9.2节架构对象名称"中的描述引用保留字,则可以将它们用作标识符:
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)
这篇关于MySQL,在查询中安全地使用保留字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!