返回行为零而不是没有结果

时间:2013-12-09 22:17:31

标签: php mysql

我的查询看起来完全像这样:

SELECT aid, 
  COALESCE(SUM(s.amount),0) AS total_spend 
FROM rt_spends AS s 
WHERE `aid` = 7 
  AND `date` BETWEEN '2013-12-01' AND '2013-12-09' 
GROUP BY s.aid

返回的内容如下:

aid | total_spend
7       100.00

但是,如果该日期范围内的记录为零。我想输出诸如

之类的东西
aid | total_spend
7       0.00

这会更适合PHP或MySQL吗?

4 个答案:

答案 0 :(得分:1)

这会有效,并且鉴于它对于简单的SUM查询来说非常复杂,我认为它也说明了在PHP中处理“无结果”可能会更好:)

SELECT aid, SUM(s.amount) AS total_spend
FROM (
  SELECT amount FROM rt_spends
    WHERE aid = 7 AND `date` BETWEEN '2013-12-01' AND '2013-12-09'
  UNION SELECT 7, 0
) s
GROUP BY s.aid

答案 1 :(得分:0)

将COALESCE改为IFNULL。

Coalesce用于比较,您可以选择。

答案 2 :(得分:0)

说明arkascha的评论:

SELECT *
FROM (
  (SELECT aid, 
    COALESCE(SUM(s.amount),0) AS total_spend 
  FROM rt_spends AS s 
  WHERE `aid` = 7 
    AND `date` BETWEEN '2013-12-01' AND '2013-12-09' 
  GROUP BY s.aid)

  UNION ALL

  (SELECT aid, 0 AS total_spend WHERE `aid` = '7')
) sub_query
LIMIT 1

答案 3 :(得分:0)

我会沿着这条路走,但我对语法的记忆并不是最好的:

SELECT aid, 
  COALESCE(sub.total_spent,0) AS total_spend 
FROM rt_spends AS s 
    LEFT JOIN (
        SELECT SUM(rt_spends.amount) AS total_spent
        FROM rt_spends 
        WHERE `aid` = 7 
            AND `date` BETWEEN '2013-12-01' AND '2013-12-09'
        GROUP BY rt_spends.aid
    ) AS sub
WHERE `aid` = 7 
GROUP BY s.aid

IMO虽然,你可能最好在PHP中这样做,为什么当没有任何东西可以让MySQL完成工作时呢?

你正在传递援助,所以如果'total'为null就做你想做的事。我认为您需要在查询中处理此问题的唯一原因是,如果您从数据库中提取更多信息,这只是它的一个元素,即即使没有支出金额,您也需要记录返回其他内容但是如果你需要总金额,但只是在日期之间 - 这就是为什么我会沿着子查询路线。