postgresql 错误:无法找到从未知到文本的转换函数

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

ERROR: failed to find conversion function from unknown to text

sqlpostgresqltypescastingunion

提问by Padagomez

There is an error on PostgreSQL that it gives on one of my select statements. I searched the web for an answer and came out empty handed. The answer given in another question did not suit my problem.

PostgreSQL 上有一个错误,它在我的一个 select 语句中给出。我在网上搜索答案,结果空手而归。在另一个问题中给出的答案不适合我的问题。

ERROR:  failed to find conversion function from unknown to text
********** Error **********
ERROR: failed to find conversion function from unknown to text
SQL state: XX000
ERROR:  failed to find conversion function from unknown to text
********** Error **********
ERROR: failed to find conversion function from unknown to text
SQL state: XX000

My query looks something like this:

我的查询如下所示:

Select * 
from (select 'string'  as Rowname, Data
      From table)
Union all
     (select 'string2' as Rowname, Data
      From table)

The point of doing this is to specify what the row is at one point. The string being the name of the row. Here is my desired output:

这样做的目的是在某一点指定行是什么。该字符串是行的名称。这是我想要的输出:

Rowname Data 
string  53
string2 87

Any possible way to fix this error?

任何可能的方法来修复这个错误?

回答by Erwin Brandstetter

Your statement has a couple of problems. But the error message implies that you need an explicit castto declare the (yet unknown) data type of the string literal 'string':

你的陈述有几个问题。但是错误消息暗示您需要显式转换来声明字符串文字的(但未知)数据类型'string'

SELECT text 'string' AS rowname, data FROM tbl1
UNION ALL
SELECT 'string2', data FROM tbl2

It's enough to cast in one SELECTof a UNIONquery. Typically the first one, where column names are also decided. Subsequent SELECTlists with unknown types will fall in line.

在查询之一SELECT中进行转换就足够了UNION。通常是第一个,其中还决定了列名。SELECT具有未知类型的后续列表将符合要求。

In other contexts (like the VALUESclause attached to an INSERT) Postgres derives data types from target columns and tries to coerce to the right type automatically.

在其他上下文中(如VALUES附加到 an的子句INSERT)Postgres 从目标列派生数据类型并尝试自动强制转换为正确的类型。

回答by Marcelo P. Llanos C.

Select * from (select CAST('string' AS text) as Rowname, Data
  From table) Union all
 (select CAST('string2' AS text) as Rowname, Data
  From table)

Reference

参考