MySQL,在查询中安全地使用保留字 [英] MySQL, safely using reserved word in query

查看:44
本文介绍了MySQL,在查询中安全地使用保留字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆