mysql中替代null的IFNULL()与COALESCE()函数详解
在MySQL中isnull()
函数不能作为替代null值!
如下:
首先有个名字为business的表:
SELECT ISNULL(business_name,'no business_name') AS bus_isnull FROM business WHERE id=2
直接运行就会报错:
错误代码: 1582
Incorrect parameter count in the call to native function 'isnull'
所以,isnull()
函数在mysql中就行不通了。可以用ifnull()
和coalesce()
代替。如下:
使用ifnull()
函数:
SELECT IFNULL(business_name,'no business_name') AS bus_ifnull FROM business WHERE id=2
运行结果:
当查询的值不为null时:
SELECT IFNULL(business_name,'no business_name') AS bus_ifnull FROM business WHERE id=1
结果如下:
使用coalesce()
函数:
SELECT COALESCE(business_name,'no business_name') AS bus_coalesce FROM business WHERE id=2
结果如下:
当查询值不为null时:
SELECT COALESCE(business_name,'no business_name') AS bus_coalesce FROM business WHERE id=1
其中:coalesce()
还可以返回第一个不为null的值。如下:
SELECT COALESCE(business_name,district_id,id) AS bus_coalesce FROM business WHERE id=2
那么,isnull()
在mysql中怎么用呢?答案就是用在where后面。如下:
SELECT * FROM business WHERE ISNULL(business_name)
结果如下:
同样,is null
和is not null
也是用在where后面。
SELECT * FROM business WHERE business_name IS NULL
结果如下:
SELECT * FROM business WHERE business_name IS NOT NULL
总结
相关推荐
Justdoit00 2020-07-04
Streamoutput 2019-12-05
lonyness 2018-12-12
北桥源木 2012-10-23
RiverCode 2018-08-20
caoyhao 2015-04-01
Before 2013-10-20
PoPoCandy 2013-03-09
81500491 2012-12-22
jesseyoung 2012-12-19
rmrfmysql 2019-04-15
cxiaole 2019-04-14
jjwwMySQL 2019-04-06
oracle 2007-01-20