在交织在一起的日期范围内快捷多个Mysql SUMS

时间:2013-03-25 05:39:48

标签: php mysql sql

当我网站上的用户登录时,会对统计信息执行多个查询。

SELECT SUM(earnings) FROM stats WHERE date BETWEEN $start_month AND $end_month
SELECT SUM(earnings) FROM stats WHERE date BETWEEN $start_last_month AND $end_last_month
SELECT SUM(earnings) FROM stats WHERE date BETWEEN $start_year AND NOW()
//etc...

我觉得我通过在单独的查询中询问SUM所有这些来“欺骗”Mysql引擎。例如,当它计算年度收入时,它也在计算其中的月收入......但是我仍然会再次查询它。

是否有更好的方法来获取交织在一起的多个日期范围的SUMS?

1 个答案:

答案 0 :(得分:3)

实际上,您可以使用CASE来计算earning

SELECT  SUM(CASE WHEN date BETWEEN $start_month AND $end_month THEN earnings ELSE 0 END),
        SUM(CASE WHEN date BETWEEN $start_last_month AND $end_last_month THEN earnings ELSE 0 END),
        SUM(CASE WHEN date BETWEEN $start_year AND NOW() THEN earnings ELSE 0 END)
FROM    stats