简体   繁体   中英

Faster way of selecting by date MYSQL

Right now I'm using:

MONTH(timestamp) = '7'AND YEAR(timestamp) = '2013'

To select by date but I've been told this is a very inefficient way of going about it, especially with a large amount of data. What is a faster way of obtaining the same results?

Thanks.

Create an index on timestamp and then use:

where timestamp >= '2013-07-01' and timestamp < '2013-08-01'

This will use the index and perform well.

You create the index as:

create index <your table name>_timestamp on <your table name>(timestamp);

The problem is that it applies a function on every comparison. You can fix this with:

  1. Not calling a function:

     where timestamp between date '2013-07-01' and date '2013-07-31' 
  2. Another way: create funcitonal index:

     create index myIndex on myTable(MONTH(timestamp),YEAR(timestamp)); 

For info: Is it possible to have function-based index in MySQL?

Search for the range of dates, inclusive of 7/1 and exclusive of 8/1.

WHERE timestamp >= '2013-07-01' and timestamp < '2013-08-01'

Mysql helpfully automatically parses the date from YYYY-MM-DD foramt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM