在我的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 WHEN
对1 != 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 null
和is not null
。
回到您的查询。is not distinct from
和is 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",但是一个计数意味着一个计数。如果你想计算用户的正确和错误答案,使用count
和filter
。
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