1

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

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 引擎。例如,当它计算年收入时,它也在计算其中的月收入......但无论如何我都会再次查询它。

有没有更好的方法来获取相互交织的多个日期范围的总和?

4

1 回答 1

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
于 2013-03-25T05:42:24.607 回答