SQL 在 Postgres 中转义类似关键字的列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7651417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:20:56  来源:igfitidea点击:

Escaping keyword-like column names in Postgres

sqlpostgresql

提问by shybovycha

If the column in Postgres' table has the name year, how should look INSERTquery to set the value for that column?

如果 Postgres 表中的列具有 name year,那么INSERT查询应该如何设置该列的值?

E.g.: INSERT INTO table (id, name, year) VALUES ( ... );gives an error near the yearword.

例如:INSERT INTO table (id, name, year) VALUES ( ... );年份字附近给出错误。

回答by NPE

Simply enclose yearin double quotes to stop it being interpreted as a keyword:

只需year用双引号括起来即可阻止它被解释为关键字

INSERT INTO table (id, name, "year") VALUES ( ... );

From the documentation:

文档

There is a second kind of identifier: the delimited identifier or quoted identifier. It is formed by enclosing an arbitrary sequence of characters in double-quotes ("). A delimited identifier is always an identifier, never a key word. So "select" could be used to refer to a column or table named "select", whereas an unquoted select would be taken as a key word and would therefore provoke a parse error when used where a table or column name is expected.

还有第二种标识符:分隔标识符或带引号的标识符。它是通过用双引号 (") 将任意字符序列括起来而形成的。分隔标识符始终是标识符,而不是关键字。因此,“select”可用于引用名为“select”的列或表,而未加引号的 select 将被视为关键字,因此在需要表名或列名的地方使用时会引发解析错误。

回答by Mayur

If you are not providing quotes in any Fields/Columns, It will be lowercased by Postgres by default. And Postgres will skip checking keyword when it comes to the column name.

如果您没有在任何字段/列中提供引号,则默认情况下 Postgres 会将其小写。当涉及到列名时,Postgres 将跳过检查关键字。

In your case, I don't think it's mandatory to add quotes when it comes to the columns. But if you are using keywords(registered by Postgres) as the name of Table, Schema, Functionor Triggeretc, you must have to use either double quotes, or you can specify schema name with dot concatenation.

在您的情况下,我认为在columns. 但是,如果您使用keywords(由 Postgres 注册)作为、或等的名称Table,则必须使用双引号,或者您可以使用点连接指定模式名称。SchemaFunctionTrigger

Let's Suppose, orderis the keyword registered by Postgres. And in some scenarios, you must have to use this keyword as a table name.

假设,order是 Postgres 注册的关键字。并且在某些情况下,您必须使用此关键字作为表名。

At that time, Postgres will allow you to create a table with keywords. That is the beauty of Postgres.

届时,Postgres 将允许您创建一个带有keywords. 这就是 Postgres 的美妙之处。

To access the order table, Either you have to use a Double quote or you can you schema name before table name.

要访问订单表,您必须使用双引号,或者您可以在表名之前使用架构名称。

E.G.

例如

1.

1.

select * from schema_name.order;

2.

2.

select * from "order";

Likewise, you can use this type of combination. Hope this will help you.

同样,您可以使用这种类型的组合。希望这会帮助你。