SQL语句中的反引号和方括号有什么区别?

What is the difference between the backtick and the square bracket in SQL statements?(SQL语句中的反引号和方括号有什么区别?)
本文介绍了SQL语句中的反引号和方括号有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我以为会有另一个问题,但我找不到.在 MySQL 和 PHP 中,我通常用反引号封装我的字段名称以屏蔽任何保留的名称或字符.但是,我的一位同事指出,这也可以使用方括号来实现.排除反引号与 SQL Server 不兼容的事实(显然),有什么区别?我应该使用哪个?

SELECT `username` FROM `users`从 [用户] 中选择 [用户名]

解决方案

SQL Server/T-SQL 使用方括号(以及 MS Access),而 MySQL 使用反引号.

据我所知,可以出现在文档中,或者在测试,方括号对 MySQL 无效.因此,如果您需要在 SQL Server 中将关键字作为表名括起来,请使用 [],而在 MySQL 中,当启用 ANSI_QUOTES 时,请使用反引号或双引号.

来自文档:

<块引用>

标识符引号字符是反引号(`"):

mysql>SELECT * FROM `select` WHERE `select`.id >100;

<块引用>

如果启用了 ANSI_QUOTES SQL 模式,也允许在双引号内引用标识符:

mysql>创建表测试"(col INT);错误 1064:您的 SQL 语法有错误...mysql>设置 sql_mode='ANSI_QUOTES';mysql>创建表测试"(col INT);查询正常,0 行受影响(0.00 秒)

I thought there would be another question about this but I was unable to find one. In MySQL with PHP I usually encapsulate my field names with backticks to mask any reserved names or characters. However, one of my colleagues has pointed out that this can also be achieved using square brackets. Excluding the fact that the backticks are not compatible with SQL server (apparently), what is the difference? Which should I use?

SELECT `username` FROM `users`
SELECT [username] FROM [users]

解决方案

SQL Server/T-SQL uses square brackets (as well as MS Access), while MySQL uses backticks.

As far as I know, can turn up in documentation, or use in testing, square brackets are not valid for MySQL. So if you need to enclose a keyword as a table name in SQL Server, use [], and in MySQL use backticks, or double-quotes when ANSI_QUOTES is enabled.

From the documentation:

The identifier quote character is the backtick ("`"):

mysql> SELECT * FROM `select` WHERE `select`.id > 100;

If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:

mysql> CREATE TABLE "test" (col INT);
ERROR 1064: You have an error in your SQL syntax...
mysql> SET sql_mode='ANSI_QUOTES';
mysql> CREATE TABLE "test" (col INT);
Query OK, 0 rows affected (0.00 sec)

这篇关于SQL语句中的反引号和方括号有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)