简体   繁体   English

按日期选择MySQL的更快方法

[英]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: timestamp上创建索引,然后使用:

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? 有关信息: MySQL中是否可以有基于函数的索引?

Search for the range of dates, inclusive of 7/1 and exclusive of 8/1. 搜索日期范围,包括7/1和8/1。

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

Mysql helpfully automatically parses the date from YYYY-MM-DD foramt. Mysql会自动从YYYY-MM-DD格式中自动解析日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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