数字等于null时使用case

  • 本文关键字:case null 数字 postgresql
  • 更新时间 :
  • 英文 :


在我的Postgres数据库中,我通过检查两个id, user_answered_id"one_answers"expected_answer_id"是等价的。如果用户没有提供"user_answered_id",那么我们仍然将他们的答案标记为不正确。

在Postgres中,下列查询

select case when 1 != null then TRUE else FALSE end as test;

select case when 1 = null then TRUE else FALSE end as test;

都导致FALSE. 这对于任何数字检查(例如,when 2 != null, when 3 != null, ...等)都是正确的。

为什么CASE WHEN1 != null不显示TRUE ?

我必须输入"支票"还是"为空"?例如,

CASE WHEN 
user_answered_id != expected_answer_id 
OR user_answered_id IS NULL 
THEN TRUE 
ELSE FALSE 
END as user_incorrect_tally

您要查找的是:is DISTINCT FROM


select 2 is distinct from  null;
?column? 
----------
t
select 2 is distinct from  1;
?column? 
----------
t

From the docs:

数据类型不同于数据类型→布尔值不相等,将null视为可比较的值。

1是DISTINCT FROM NULL→t(而不是NULL)

NULL是DISTINCT FROM NULL→f(而不是NULL)

SQL使用三值逻辑:true, false和null。Null不是false。Null可以理解为"没有值"。

对null的操作几乎总是产生null。所以1 != null是空的。1 = null为空。null = null为空。5 < null为空。等。

检查是否为空,使用is nullis not null


回到您的查询。is not distinct fromis distinct from类似于=!=,它们将null作为可比较的值。因此,null is distinct from 1将为true。

select
user_answered_id is distinct from expected_answer_id as user_incorrect

如果您需要将null转换为不同的值,例如0或空字符串,请使用coalesce

select
coalesce(user_answered_text, 'No Answer')

您的列被命名为"tally",但是一个计数意味着一个计数。如果你想计算用户的正确和错误答案,使用countfilter

select
count(user_answered_id) filter (
where user_answered_id = expected_answer_id
) as user_correct_tally,
-- count ignores null, this will only be the questions they tried to answer
count(user_answered_id) as user_answered_tally,
count(user_answered_id) filter (
where user_answered_is is distinct from expected_answer_id
) as user_incorrect_tally

是的,你应该用is null检查NULL值,最后你写的查询是正确的。

我建议你阅读下面文件:

https://www.postgresql.org/docs/current/functions-comparison.html

最新更新