case when then 中判断null的方法

MYSQL 中使用case when then 判断某字段是否为null,和判断是否为字符或数字时的写法不一样,如果不注意,很容易搞错

错误方法:

CASE columnName WHEN null THEN 0 ELSE columnName END

正确方法:

CASE WHEN columnName is null THEN 0 ELSE columnName END


1.SELECT CASE WHEN min(id) IS NULL THEN 0 ELSE min(id) END AS min_id,
   CASE WHEN max(id) IS NULL THEN 0 ELSE max(id) END AS max_id
   FROM stat_user WHERE  stat_time between 2016102310 and 2016122410

2.select ifnull(min(id),0),ifnull(max(id),0) FROM stat_user WHERE  stat_time between 2016102310 and 2016122410

用ifnull这个函数效率会更高一些!

    原文作者:yibanbairimeng
    原文地址: https://blog.csdn.net/yibanbairimeng/article/details/54408790
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞