MySQL中的IFNULL用法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL中的IFNULL用法相关的知识,希望对你有一定的参考价值。

参考技术A IFNULL(expr1,expr2)
如果 expr1 不是 NULL,IFNULL() 返回 expr1,否则它返回 expr2。
IFNULL()返回一个数字或字符串值,取决于它被使用的上下文环境。

例子:

说明:IFNULL只有mysql中有,hive中并没有此用法。

mysql ifnull语句

SELECT a.*, c.order_number from `table_a` as a left join (select partner_id, IFNULL(count(order_id),0) as order_number from `table_c` group by partner_id) as c on c.partner_id=a.partner_id

为什么得到的结果中 order_number 是null,而不是我想要的0
表c 是空的,只有结构,没有数值

参考技术A left join没有关联到的都会置成NULL, 跟你ifnull没有关系

写在最外层才有效果,像这样
SELECT a.*, ifnull(c.order_number,0) from `table_a` as a left join (select partner_id, IFNULL(count(order_id),0) as order_number from `table_c` group by partner_id) as c on c.partner_id=a.partner_id本回答被提问者和网友采纳
参考技术B 首先,
你的语句中,完全没有必要使用ifnull(),
因为count()函数不会返回null值,只会返回>=0的整数。
其次,
结果中出现null的原因,并不是应为c.order_number的值,而是:
left join的时候,如果在右表中找不到对应的内容,就会显示null,
正是因为你的表c是空的,所以...
希望你能明白!

以上是关于MySQL中的IFNULL用法的主要内容,如果未能解决你的问题,请参考以下文章

mysql ifnull语句

mysql中ifnull的用法

mysql ifnull 用法

MySql数据库ifnull的用法

mysql几个常用的判空函数:isnull, ifnull, nullif, coalesce

mysql ifnull 函数 使用和 if 三目运算