我有一个完全像这样的查询:

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?

最佳答案

这将起作用,而且考虑到对于一个简单的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

关于php - 返回零而不是结果的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20482032/

10-16 14:13