:: 在 PostgreSQL 中有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15537709/
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-11 00:06:09  来源:igfitidea点击:

What does :: do in PostgreSQL?

postgresqlsyntaxtypescastingtypecast-operator

提问by ams

I have seen ::in variety of places involving postgres code I have seen on the net. For example:

::在网上看到过很多涉及 postgres 代码的地方。例如:

SELECT '{apple,cherry apple, avocado}'::text[];

It seems to be some sort of cast. What exactly is ::in postgres and when should it be used?

这似乎是某种类型的演员。::postgres到底是什么,什么时候应该使用它?

I tried a bit of googling and searched the Postgres docs for ::but got no good results.
I tried following searches in Google:

我尝试了一些谷歌搜索并搜索了 Postgres 文档,::但没有得到好的结果。
我尝试在 Google 中进行以下搜索:

  • postgres double colon
  • postgres ::
  • ::
  • postgres 双冒号
  • postgres ::
  • ::

I tried the following searches in the postgres docs search button

我在 postgres 文档搜索按钮中尝试了以下搜索

  • double colon
  • double colon cast
  • ::
  • 双冒号
  • 双冒号
  • ::

This was almost embarrassing to ask on SO, but I figured Google will hopefully see this answer for other people in the future.

在 SO 上问这个问题几乎令人尴尬,但我认为 Google 有望在未来为其他人看到这个答案。

回答by PSR

A type cast specifies a conversion from one data type to another.

类型转换指定从一种数据类型到另一种数据类型的转换。

PostgreSQL accepts two equivalent syntaxes for type casts, the PostgreSQL-specific value::typeand the SQL-standard CAST(value AS type).

PostgreSQL 接受两种等效的类型转换语法,PostgreSQL-specificvalue::type和 SQL-standard CAST(value AS type)

In this specific case, '{apple,cherry apple, avocado}'::text[];takes the string literal {apple,cherry apple, avocado}and tells PostgreSQL to interpret it as an array of text.

在该特定情况下,'{apple,cherry apple, avocado}'::text[];需要字符串文字{apple,cherry apple, avocado}并告诉PostgreSQL的把它解释为一个阵列text

See the documentation on SQL expressionsand arraysfor details.

有关详细信息,请参阅有关SQL 表达式数组的文档。

回答by Erwin Brandstetter

What @PSR and @Craig wrote.
Plus, there are two more syntax variants:

@PSR 和 @Craig 写了什么
另外,还有两种语法变体

1. type valuetype value

This form only casts constants (string literals). Like in:

这种形式只转换常量(字符串文字)。像:

SELECT date '2013-03-21';

More in the manual in the chapter Constants of Other Types.

更多内容请参见其他类型常量一章的手册。

2. type(value)type(value)

That's the function-like syntax. Works only for types whose names are valid as function names. Like in:

这就是类似函数的语法。仅适用于名称作为函数名称有效的类型。像:

SELECT date(date_as_text_col) FROM tbl;

More in the manual in the chapter Type Casts.

更多信息请参阅Type Casts一章的手册。

More comprehensive answer:

更全面的答案: