2016-02-04 50 views
0

嘿家伙我有一个关于sql性能的快速问题。我有一个非常非常大的表,它永远运行下面的查询,请注意,有一个与时间戳列mysql tunning时间戳性能?

select name,emails, 
    count(*) as cnt 
from table 
where date(timestamp) between '2016-01-20' and '2016-02-3' 
and name is not null 
group by 1,2; 

所以,我的朋友建议使用下面这个查询:

select name,emails, 
    count(*) as cnt 
from table 
where timestamp between date_sub(curdate(), interval 14 day) 
and date_add(curdate(), interval 1 day)  
and name is not null 
group by 1,2; 

而且这需要更少的时间来运行。为什么?这两个时间函数有什么区别? 还有另一种更快的运行方式吗?像索引?有人可以向我解释mysql如何运行?非常感谢!

+2

在我的文章中也包含了对这两个查询的解释以及对于这些问题的创建表语句 – Shadow

+0

检查原因... –

回答

1

只需添加上timestamp场指数和使用查询按如下─

select name,emails, 
    count(*) as cnt 
from table 
where `timestamp` between '2016-01-20 00:00:00' and '2016-02-03 23:59:59' 
and name is not null 
group by 1,2; 

为什么?这两个时间函数有什么区别

在第一个查询中,您从自己的列中获取日期,但使用date()函数由于这个原因,mysql没有使用索引并进行表扫描,而第二个建议的表已被删除date(timestamp)函数,所以现在mysql会检查索引中的值而不是表扫描,因此速度很快。

相同的mysql也会在我的表中使用索引。