postgresql 插入比较NULL值的数据时出现问题

n7taea2i  于 6个月前  发布在  PostgreSQL
关注(0)|答案(1)|浏览(92)

我在插入比较NULL值的数据时遇到问题。
我有一个目标表fact_jpm_莱亚_temp和staging表debug_fact_jpm_lea_temp1
我的疑问是

insert into fact_jpm_lea_temp 

select
SFS.employee_id,
SFS.shift_date,
SFS.sch_time_in,
SFS.sch_time_out,
now() as dwh_ins_ts ,
now() as dwh_updt_ts
from
debug_fact_jpm_lea_temp1 as SFS
where
not exists (
select
*
from
fact_jpm_lea_temp DFS
where
DFS.employee_id = SFS.employee_id
and DFS.shift_date = SFS.shift_date
and DFS.sch_time_in = SFS.sch_time_in
and DFS.sch_time_out = SFS.sch_time_out
and dfs.sch_time_in is null and dfs.sch_time_out is null

)

``
我已经在我的目标表中有一个记录,如下所示,其中time in和time out为null,并且在staging table中也相同,我添加了额外的条件dfs. sch_time_in为null,dfs.sch_time_out也为null,以消除但仍然不起作用。188040 12/11/2023 2023 - 12 - 18 13:33:17.248 -0600 2023-12-18 13:33:17.248 -0600
和staging表中的值相同
当我尝试插入它时,它只是继续插入,即使它不应该插入,因为我的暂存表和目标表数据都匹配。
如果雇员id、shift_Date、time_in和time_out匹配,则不应插入?

toe95027

toe950271#

SQL使用three valued logic。有truefalsenullwhere语句检查真值,而null不是true。因此这个where子句过滤掉所有行:

where   null = null

字符串
令人惊讶的是,任何与null的比较也会返回null。因此,以下所有where子句都会过滤掉所有行:

where   1 <> null
where   null < 1
where   1 in (1, 2, null)


一个典型的处理方法是将null值从coalesce中删除:

coalesce(DFS.shift_date, '1970-01-01') = coalesce(SFS.shift_date, '1970-01-01')


或者使用is null检查null

(DFS.shift_date = SFS.shift_date OR 
    (DFS.shift_date IS NULL AND SFS.shift_date IS NULL))


或者正如@JohnH在评论中优雅地建议的那样,Postgres特定的解决方案是is distinct from

DFS.shift_date is not distinct from SFS.shift_date

相关问题