意外行为:空值之间的减法导致'0'

时间:2013-08-23 14:41:03

标签: mysql sql

当其中一个字段为NULL时,我希望返回的值也是NULL。我也试过逆转逻辑:is not null。结果仍然相同。

MySQL代码:

(case
            when
                ((`creative_stg_sample_tracking_raw`.`total_samples_received` is not null)
                    and (`creative_stg_sample_tracking_raw`.`total_samples_forecasted` is not null))
            then
                (cast(`creative_stg_sample_tracking_raw`.`total_samples_received`
                    as signed) - cast(`creative_stg_sample_tracking_raw`.`total_samples_forecasted`
                    as signed))
            else NULL
        end) AS `received_forecasted_dif`

截图:

screenshot

1 个答案:

答案 0 :(得分:1)

您的代码应该正常运行,但您不需要case。每当其中一个值为NULL时,表达式应为NULL

(cast(`creative_stg_sample_tracking_raw`.`total_samples_received` as signed) -
 cast(`creative_stg_sample_tracking_raw`.`total_samples_forecasted` as signed))
) AS `received_forecasted_dif`

我想知道您的问题是该值实际上是'NULL'而不是NULL。也就是说,字符串值而不是真正的NULL。 MySQL会在算术中将字符串视为0

您可以通过执行以下操作来解决此问题:

(case when `creative_stg_sample_tracking_raw`.`total_samples_received` <> 'NULL' and
           `creative_stg_sample_tracking_raw`.`total_samples_forecasted` <> 'NULL'
      then (cast(`creative_stg_sample_tracking_raw`.`total_samples_received` as signed) -
            cast(`creative_stg_sample_tracking_raw`.`total_samples_forecasted` as signed))
           )
      else NULL
end) AS `received_forecasted_dif`