简体   繁体   English

MySQL SELECT特定年份的月份

[英]MySQL SELECT Month from a particular year

Yes I've read the docs here 是的我在这里阅读了文档

I have the following query: 我有以下查询:

SELECT * FROM db.table
WHERE event_type = 3
AND (YEAR(event_time) = 2014 AND MONTH(event_time) = 10)

This returns all records from October 2014. Great. 这将返回2014年10月以来的所有记录。很棒。 Only wanted to ask, is there a shorter, better or neater way than having to write (YEAR(event_time) = 2014 AND MONTH(event_time) = 10) ? 只想问一下,是否有比写作更短,更好或更简洁的方式(YEAR(event_time) = 2014 AND MONTH(event_time) = 10) Is this the "conventional" way of extracting a particular month in a given year? 这是在某一年中提取特定月份的“常规”方式吗?

Learning here. 在这里学习。

If you have an index on the event_time column, using YEAR and MONTH (or pretty much any function) will prevent the index being used to optimize the query fully. 如果在event_time列上有索引,则使用YEARMONTH (或几乎任何函数)将阻止使用索引来完全优化查询。 Something like this will be fastest; 这样的事情会最快; I'll leave it to you to determine if it's neatest: 我会留给你确定它是否是最好的:

SELECT * FROM db.table
WHERE event_type = 3
  AND event_time >= '2014-10-01' AND event_time < '2014-11-01'

That will give you everything in October 2014, and it's fully optimizable. 这将在2014年10月为您提供一切,并且完全可以优化。

You can create a temporary view using the with clause of the records in the year 2014 and then extract only October from that view. 您可以使用2014年记录的with子句创建临时视图,然后仅从该视图中提取10月。

Because everytime the query needs to check if it is 2014 and month October. 因为每次查询都需要检查是否是2014年和10月。

So I think views will do it better. 所以我认为观点会做得更好。

Also you can enhance the performance by adding index 您还可以通过添加索引来增强性能

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

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