Home >Database >Mysql Tutorial >mysql ifnull

mysql ifnull

WBOY
WBOYOriginal
2016-06-07 16:34:561478browse

mysql内置的ifull函数可以用在查询时候为NULL值字段给一个默认值,例如: select ifnull(col1, 'default-value'), col2 from test; 当test表的col1字段为NULL时,数据库返回的结果就为default-value,否则就返回本身的值。但是当col1字段的值为空字符串(”

mysql内置的ifull函数可以用在查询时候为NULL值字段给一个默认值,例如:

select ifnull(col1, 'default-value'), col2 from test;

当test表的col1字段为NULL时,数据库返回的结果就为default-value,否则就返回本身的值。但是当col1字段的值为空字符串(”),由于空字符不是NULL,因此返回的结果还是空字符串。如果需要把空字符串或NULL值都用default-value代替,显然ifnull是不行,不过使用case when语句能搞定,示例如下:

select c1,
(case when c2 = '' or c2 is null then 'default-value' else  c2 end)
from test;
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn