数据库中经常有字段type为null ,对于统计count(type)和avg(type) 都不起作用
sql中有isnull方法,介绍如下:
isnull
使用指定的替换值替换 null。
语法
isnull ( check_expression , replacement_value )
参数
check_expression
将被检查是否为 null的表达式。check_expression 可以是任何类型的。
replacement_value
在 check_expression 为 null时将返回的表达式。replacement_value 必须与 check_expresssion 具有相同的类型。
例如:
select count(isnull(weight, 50)) from product;
但是在mysql中,isnull只是用来判断是否为空,不能实现替换功能,照上面写的话,会直接报错(incorrect parameter count in the call to native function 'isnull' errornumber:1582 )。
那么mysql中如何实现sql中的isnull方法呢?ifnull( check_expression , replacement_value ),实现了sql中的isnull方法。
还是上面的例子:
select count(ifnull(weight, 50)) from product;
就好了,就这样。