简体   繁体   中英

How to select mySQL records based only on month and year without full table scan

I need to select records based on the month and year, The month and the year will come from PHP

so I have the query like

SELECT id, created FROM table_name WHERE YEAR(created) = 2020 AND MONTH(created) = 05 LIMIT 500;

Here created is the datetime field, The problem with this query is, It is working fine if the table has less records but when table records are increasing the query is becoming very slow

I have more than 10,000 records in my table for 2020-05 and a total of 1 million records so it takes approx 11 seconds to execute this query, I suspect this is because the query is doing a full table scan

Help me with a solution to make this query execute faster?

You are using YEAR() and MONTH() function in where clause when using a function in where clause MySQL doesn't use the index of that column to executing your query.

You can change your query to below and make a try

SELECT id, created FROM table_name WHERE created between '2020-05-01 00:00:00' and '2020-05-31 23:59:59'

** Don't forget to add an index to your field.

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