Postgresql - NULL的解释类型错误

时间:2016-04-28 09:49:03

标签: postgresql postgresql-9.2

我遇到以下CTE表达式的问题,因为 defaultConfig { multiDexEnabled true } 中的prev_count被解释为new_values,但我在text中更新的列是输入counts。我在标记的行上收到此错误:

integer

以下是查询:

ERROR:  column "prev_count" is of type integer but expression is of type text
LINE 12:     prev_count = new_values.prev_count

我的问题是,修复错误的优雅方法是什么?我宁愿在WITH new_values (word,count,txid,prev_count) AS ( VALUES ('cat',1,5,NULL)), updated AS ( UPDATE counts t SET count = new_values.count, txid = new_values.txid, prev_count = new_values.prev_count -- ERROR HERE FROM new_values WHERE ( t.word = new_values.word ) RETURNING t.*) INSERT INTO counts( word,count,txid,prev_count ) SELECT word,count,txid,prev_count FROM new_values WHERE NOT EXISTS ( SELECT 1 FROM updated WHERE (updated.word = new_values.word)) 中指定prev_count的类型,而不是添加明确的演员,但我在文档中看不到类似的内容。

1 个答案:

答案 0 :(得分:2)

在此处添加此内容作为明确答案以及详细说明。

修复方法是:

WITH  
    new_values (word,count,txid,prev_count) AS (
        VALUES ('cat',1,5,NULL::text)),

在评论中建议使用a_horse_with_no_name。

为什么这有必要?因为行规范来自VALUES部分,NULL是未知的。在这种情况下,PostgreSQL有助于转换为文本。但这不是你想要的,所以你必须给NULL一个类型。

这通常也出现在其他情况下,例如UNION语句,其中列列表中第一个段中的NULL可以被赋予一个隐式类型,该类型与另一个段中的列类型相冲突。所以这是一个值得了解的棘手角落。