0

当值的列之一仅包含Null值时,需要帮助来解决问题。例子:

create table foo (
    id serial constraint foo_pk primary key,
    a int,
    b int
);

insert into foo (a,b) values (1, 1), (2, 2);

update foo t
set a = v.a, b = v.b
from (values (1, NULL, 1),(2, NULL, 2)) as v(id, a, b)
where v.id = t.id;

这给了我:

[42804] ERROR: column "a" is of type integer but expression is of type text 
Hint: You will need to rewrite or cast the expression. Position: 22

我正在使用psycopg2.extras.execute_values以更新多个 Django ORM 对象。寻找不需要将空值显式转换为字段类型的解决方案。

4

1 回答 1

0

由于您为 column 传递的所有值a都是NULLs ,所以 Postgres 会隐含地认为它们是TEXTs

你有2个选择,

在表达式中将 的值强制a转换为 int 。SET

set a = v.a::int

或者

将其中一个值转换为ato INT,其他值将默认为该值。

values (1, NULL::int, 1),(2, NULL, 2)) as v(id, a, b)

演示

于 2019-05-24T03:36:00.203 回答