Home >Database >Mysql Tutorial >MySQL Left JOIN时指定NULL列返回特定值

MySQL Left JOIN时指定NULL列返回特定值

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-07 17:24:201094browse

我们有时会有这样的应用,需要在sql的left join时,需要使值为NULL的列不返回NULL而时某个特定的值,比如0,这个时候,用is_null

我们有时会有这样的应用,需要在sql的left join时,需要使值为NULL的列不返回NULL而时某个特定的值,比如0

这个时候,用is_null(field,0)是行不通的,会报错的,可以用ifnull实现,但是COALESE似乎更符合标准。

coalesce  函数可以接受多个参数,将会返回这些参数中第一个非NULL的值,若提供的参数全部为NULL,则返回NULL

ifnull  函数和coalesce功能一样,只是只可以接受两个参数

if  函数接受三个参数,实现类似于三元判断符(?:)的功能,即第一个参数不为NULL且不为0时,,返回第二个参数,否则返回第三个参数

SELECT a.*,coalesce(t.cous,0) as count FROM brand as a
left join (select brandid as bid,count(1) as cous from shopbrand group by brandid) t on a.brandid=t.bid
ORDER BY count DESC LIMIT 0,20

上述语法是做一个统计,本身会返回NULL,但是为空的话并不是一个好的做法,所以用coalesce来解决。

linux

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