使用IFNULL函数mysql将null设置为零

时间:2015-03-03 16:54:22

标签: mysql database ifnull

我的数据库上有以下架构的表格:

customers (customerID: integer, fName: string, lName: string)
items (itemID: integer, description: string, price: integer)
orders (orderID: integer, itemID: integer, aID: integer, customerID:integer, date: date)

和以下代码:

SELECT c.customerID, COUNT(DISTINCT o.orderID) AS number_of_orders, 
       ROUND(SUM(i.price) / COUNT(DISTINCT o.orderID),2) AS average 
  FROM customers c 
     LEFT JOIN orders o 
            ON o.customerID = c.customerID 
           AND o.date >= '2013-03-01' 
           AND o.date < '2013-04-01' 
     LEFT JOIN items i 
            ON o.itemID = i.itemID 
GROUP BY c.customerID

返回三个值:客户ID,每个客户的订单数量和每个客户的平均支出。 使用现在的代码,每个客户的平均支出将返回空白(null)。 如果客户在2013年3月没有订购任何东西(即,如果每个客户在3月份的订单数量为零),我在使用IFNULL功能将每个客户的平均支出设置为0.00时遇到问题。 任何帮助将非常感谢!

2 个答案:

答案 0 :(得分:0)

使用IF()函数可能会更好地使用案例。

SELECT c.customerID, COUNT(DISTINCT o.orderID) AS number_of_orders, 
       IF(COUNT(o.orderID) > 0,ROUND(SUM(i.price) / COUNT(DISTINCT o.orderID),2),0) AS average 
  FROM customers c 
     LEFT JOIN orders o 
            ON o.customerID = c.customerID 
           AND o.date >= '2013-03-01' 
           AND o.date < '2013-04-01' 
     LEFT JOIN items i 
            ON o.itemID = i.itemID 
GROUP BY c.customerID

答案 1 :(得分:0)

如果没有看到IFNULL次尝试,这个逻辑对我有用:

SELECT c.customerID, 
COUNT(DISTINCT o.orderID) AS number_of_orders, 
ROUND(IFNULL( (SUM(i.price) / COUNT(DISTINCT o.orderID)), 0.00),2) AS average,
FORMAT(IFNULL(ROUND( (SUM(i.price) / COUNT(DISTINCT o.orderID)),2), 0), 2) AS averageWithFormat 
FROM customers c 
LEFT JOIN orders o ON o.customerID = c.customerID AND o.date >= '2013-03-01' AND o.date < '2013-04-01' 
LEFT JOIN items i ON o.itemID = i.itemID 
GROUP BY c.customerID

返回:0.00

我的语句中有average的两个条目,因为在我的本地MySQL Workbench中,第一个返回两个小数精度但不在SQLFiddle中。我添加了第二个带有FORMAT语法的条目,以强制使用两个小数精度(如果需要)。