简体   繁体   中英

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. 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) ? 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. 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.

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.

Because everytime the query needs to check if it is 2014 and month October.

So I think views will do it better.

Also you can enhance the performance by adding index

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