以下是我的 SQL 查询:
update table
set unit_id = T1.unit_id_temp from
(select case when unit_id4 is not null then unit_id4
when unit_id3 is not null then unit_id3
when unit_id2 is not null then unit_id2
when unit_id1 is not null then unit_id1
else unit_id
end as unit_id_temp,
unit_id1,unit_id2,unit_id3,unit_id4
from table) T1
where table.unit_id4 = T1.unit_id4
and table.unit_id3 = T1.unit_id3
and table.unit_id2 = T1.unit_id2
and table.unit_id1 = T1.unit_id1
在上面的查询中,当列为 NULL 时,我无法比较它们,因为条件返回 false。
例如: 当 unit_id4 为 null 时, table.unit_id4 = T1.unit_id4 返回 False。
因此,只要任一列包含 NULL 值,我的更新就会失败。
我试过使用 is not distinct from,它不起作用。抛出以下错误:
更新 - 0 行,0.000 秒] [代码:0,SQL 状态:42601] 错误:“distinct”处或附近的语法错误
最佳答案
我想你可以用这个替换你的整个查询:
UPDATE table
SET unit_id = COALESCE(unit_id4, unit_id3, unit_id2, unit_id1)
WHERE COALESCE(unit_id4, unit_id3, unit_id2, unit_id1) IS NOT NULL
在我看来,您的逻辑是将 unit_id
列更新为 unit_id4
、unit_id3
、unit_id2
, unit_id1
,如果这些列中的任何一个不是 NULL
,则按此顺序。 COALESCE
函数适用于此用例。如果 所有 四列都是 NULL
,则 UPDATE
中的逻辑只是将相同的值分配回 unit_id
。我查询中的 WHERE
子句将阻止 UPDATE
甚至在所有四个单位列都为 NULL
的记录上运行,因此永远不会有任何白费力气。
关于POSTGRESQL 无法比较空列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38561695/