What is the most efficient way to search in date ranges in MySQL?

前端 未结 1 1559
忘了有多久
忘了有多久 2020-12-06 11:46

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:

SELE         


        
相关标签:
1条回答
  • 2020-12-06 12:11

    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)
提交回复
热议问题