如何在mysql中将null返回为零?

时间:2015-05-22 10:50:56

标签: mysql join

我希望当它为null时返回挂起为零:

SELECT `t1`.*, `t2`.`pending` as IFNULL(ending, `0)`
FROM (`tblproducts` t1)
LEFT JOIN `cache_invoice` t2 ON `t1`.`id` = `t2`.`product_id`
LEFT JOIN `cache_stock` t3 ON `t1`.`id` = `t3`.`product_id`

错误:

  

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法   靠近'(结束,0) FROM(tblproducts t1)LEFT JOIN cache_invoice   t2在第1行开启t1id'

知道问题出在哪里?

1 个答案:

答案 0 :(得分:1)

问题在于:

`t2`.`pending` as IFNULL(ending, `0)`

您正在检查IFNULL是否有该列的别名值,而它应该如下:

IFNULL(`t2`.`pending`, 0) as ending

首先评估是否为null - 然后显示0并创建别名,如果您想使用' AS'关键词。因此,您的查询将是:

SELECT `t1`.*, IFNULL(`t2`.`pending`, 0) as ending
FROM `tblproducts` t1
LEFT JOIN `cache_invoice` t2 ON `t1`.`id` = `t2`.`product_id`
LEFT JOIN `cache_stock` t3 ON `t1`.`id` = `t3`.`product_id`