用法
IFNULL(expr1,expr2);
如果第一个参数不为空则返回第一个参数的值,否则返回第二个参数的值
测试
第一个参数为空时
SELECT IFNULL(NULL, 1);
返回结果为
1
第一个参数不为空时
SELECT IFNULL("hello", 1);
返回结果为
hello
使用场景
可用于在计算时判断某个值可能为空的字段
下面演示一个例子
比如在计算一件租赁产品当月的租金金额的时候,由于数据库设计原因,没有把免租天数设计成 not null 或者没有给默认值的时候,如果不使用 IFNULL 判断就会出现月租金为 null 的情况
表内数据如下
id | p_id | rent_days | free_days | day_price |
---|---|---|---|---|
1 | 10001 | 30 | null | 18 |
不使用 IFNULL 的情况下
SELECT p_id , (rent_days - free_days) / day_price as month_price
FROM rent_order
WHERE p_id =10001
p_id | month_price |
---|---|
10001 | null |
查询的 month_price 结果为 null
使用了 IFNULL 的情况下
SELECT p_id , (rent_days - IFNULL(free_days, 0)) / day_price as month_price
FROM rent_order
WHERE p_id =10001
p_id | month_price |
---|---|
10001 | 540 |
查询的 month_price 结果为 540
注意事项
如果查询的行记录不存在,IFNULL也会返回 null