MySQL查询性能与计算的where子句

时间:2016-07-01 20:03:30

标签: mysql performance

使用MySQL,1M记录表,索引存在于' some_timestamp'。

WHERE子句使用计算,以便可以计算不同时间段的记录。

需要很长时间才能执行。

是否有更好,更快的方法???

以下是当前代码:

set @now = now();

(SELECT 
    "45 Days" as "interval", count(*) as "thecount"
    FROM blah.yada
    where TIMESTAMPDIFF(day,some_timestamp,@now) <= 45
        )

UNION
(SELECT 
    "90 Days" as "interval", count(*) as "thecount"
    FROM blah.yada
    where TIMESTAMPDIFF(day,some_timestamp,@now) > 45 and TIMESTAMPDIFF(day,event_timestamp,@now) <=90
        )

UNION
(SELECT 
    "the rest" as "interval", count(*) as "thecount"
    FROM blah.yada
    where TIMESTAMPDIFF(day,some_timestamp,@now) > 90 
        )

1 个答案:

答案 0 :(得分:1)

在这种情况下,只需重新修改一下逻辑就可以创造奇迹。

TIMESTAMPDIFF(day,some_timestamp,@now) <= 45

可以更改为

some_timestamp >= @now - INTERVAL 45 DAY

以及其余的比较等等。通过将计算移出字段,可以使用索引。

此外,您不需要多个查询和UNION。

SELECT CASE WHEN some_timestamp >= @now - INTERVAL 45 DAY THEN "45 Days"
            WHEN some_timestamp >= @now - INTERVAL 90 DAY THEN "90 Days"
            ELSE "the rest"
       END AS `interval`
     , COUNT(*) AS `theCount`
FROM blah.yada
GROUP BY `interval`
;