简体   繁体   English

如何仅基于月份和年份的 select mySQL 记录没有全表扫描

[英]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我需要基于月份和年份的 select 记录,月份和年份将来自 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 2020-05 年我的表中有超过 10,000 条记录,总共有 100 万条记录,因此执行此查询大约需要 11 秒,我怀疑这是因为查询正在执行全表扫描

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.当在 where 子句 MySQL 中使用 function 时,您在 where 子句中使用 YEAR() 和 MONTH() function 不使用该列的索引来执行查询。

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. ** 不要忘记为您的字段添加索引。

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

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