简体   繁体   English

条件 NOT NULL case SQL

[英]Conditional NOT NULL case SQL

I am trying to calculate a field and I want it to behave differently depending on if one of the columns happens to be null.我正在尝试计算一个字段,我希望它根据其中一列是否为空而表现出不同的行为。 I am using MySQL我正在使用 MySQL

CASE 
  WHEN reply.replies <> NULL THEN
  24/((UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(qcr.LAST_MOD_TIME)+3600)/3600)*(ces.EXPERT_SCORE+2.5*scs.SIMILARITY)*(EXP(-reply.replies))
  ELSE 1
END as ANSWER_SCORE

Is this the right syntax?这是正确的语法吗?

You need to have when reply.replies IS NOT NULL 你需要when reply.replies IS NOT NULL

NULL is a special case in SQL and cannot be compared with = or <> operators. NULL是SQL中的一种特殊情况,无法与=或<>运算符进行比较。 IS NULL and IS NOT NULL are used instead. 改为使用IS NULL和IS NOT NULL。

case when reply.replies IS NOT NULL ...

You can't compare NULL with the regular (arithmetic) comparison operators. 您无法将NULL与常规(算术)比较运算符进行比较。 Any arithmetic comparison to NULL will return NULL, even NULL = NULL or NULL <> NULL will yield NULL. 任何与NULL的算术比较都将返回NULL,即使NULL = NULLNULL <> NULL也将产生NULL。

Use IS or IS NOT instead. 使用ISIS NOT代替。

You can make a CASE Statement Checking Null 您可以使CASE语句检查为空

SELECT MAX(id+1),  
IF(MAX(id+1) IS NULL, 1, MAX(id+1))
AS id   
FROM `table_name`;

You don't need a case statement for this. 你不需要一个case语句。
Use the IFNULL function 使用IFNULL功能

IFNULL(24/((UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(qcr.LAST_MOD_TIME)+3600)/3600)
*(ces.EXPERT_SCORE+2.5*scs.SIMILARITY)*(EXP(-reply.replies)), 1) as ANSWER_SCORE

If reply.replies is null, the expression is shortcut to NULL 如果reply.replies为null,则表达式为NULL快捷方式
IFNULL then takes the 2nd parameter (1) and gives that as a result when it happens. 然后IFNULL接受第二个参数(1)并在结果发生时给出结果。

For other cases where you do need to compare to NULL, this will help you to work with MySQL. 对于需要与NULL进行比较的其他情况, 这将有助于您使用MySQL。

如果您在 SQL 语法中使用 is not null,则最好,'<>' 表示该列具有可与其他句子进行比较的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM