POSTGRESQL 无法比较空列

标签 postgresql amazon-redshift

以下是我的 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_id4unit_id3unit_id2 , unit_id1,如果这些列中的任何一个不是 NULL,则按此顺序。 COALESCE 函数适用于此用例。如果 所有 四列都是 NULL,则 UPDATE 中的逻辑只是将相同的值分配回 unit_id。我查询中的 WHERE 子句将阻止 UPDATE 甚至在所有四个单位列都为 NULL 的记录上运行,因此永远不会有任何白费力气。

关于POSTGRESQL 无法比较空列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38561695/

相关文章:

postgresql - Squeel 请求和 Heroku,Postgres : Error using GROUP BY and ORDER

amazon-web-services - 在 AWS CloudFormation 中定义表、 View 和索引

python-3.x - AWS Redshift : How to describe a library created in redshift?

sql - 计算具有多个条件的列的许多不同组合

amazon-web-services - 如何使用 RedShift 查询的输出作为 EMR 作业的输入?

postgresql - 模拟多对多关系的最佳方式是什么

sql - 如何编写聚合外汇蜡烛数据的查询?

mysql - 针对无法实时发生的繁重工作负载的策略? (Web 应用程序、用户匹配、缓存)

java - 使用netbeans或任何IDE通过SSH连接到远程服务器并访问Postgresql数据库以在本地计算机上执行查询

amazon-redshift - 在与 avg 相同的查询中使用中值聚合?