mysql 时间范围搜索,在MySQL中搜索日期范围最有效的方法是什么?

I'd like to ask what is the most efficient (and fastest) way to search for data between 2 dates?

Let's consider having following simple query:

SELECT Date_,counter1,counter2,...

WHERE (date range condition)

The "Date_" column is a DATETIME type.

I tried different options like:

WHERE Date_ >= '2012-12-01 00:00:00' AND Date_ <= '2012-12-05 00:00:00'

and

WHERE Date_ BETWEEN '2012-12-01 00:00:00' AND '2012-12-05 00:00:00'

and

WHERE Date_ = '2012-12-01 00:00:00' OR Date_ = '2012-12-02 00:00:00' OR

Date_ = '2012-12-03 00:00:00' OR Date_ = '2012-12-04 00:00:00' OR

Date_ = '2012-12-05 00:00:00'

In fact this Select query is a lot more complicated (with joins and more conditions). This is only the simplified version. According to EXPLAIN there is no difference, how the query is executed. I need to say that Date_ column is indexed. Unfortunately, I cannot test the real query speed, because I cannot avoid OS caching, but at least MySQL cache was not used (SQL_NO_CACHE).

Is there according to your experince a faster way to search in date intervals (without functions)?

Which of the three methods is faster (in case that there is a difference at all)?

Thanks a lot in advance!

解决方案

The big factor in efficiency is going to be the availability of suitable indexes, and the generation of an efficient execution plan.

Our normative pattern for searching a datetime range is to use a greater than and equal to, and a less than (but not equal to) comparisons.

To get all datetimes for a single day, for example, '2012-12-01', we typically code this like:

WHERE datetimecol >= '2012-12-01'

AND datetimecol < '2012-12-02'

-or-

WHERE datetimecol >= '2012-12-01'

AND datetimecol < '2012-12-01' + INTERVAL 1 DAY

Similarly, to get the five day range in your example:

WHERE datetimecol >= '2012-12-01'

AND datetimecol < '2012-12-06'

-or-

WHERE datetimecol >= '2012-12-01'

AND datetimecol < '2012-12-01' + INTERVAL 5 DAY

To answer your question, "is there a faster way?" No. A predicate of that form enables MySQL to perform a range scan on an index (given a suitable index available.) It doesn't get any more efficient than that.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值