Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
优化MySQL查询性能_Mysql_Sql_Indexing_Query Performance - Fatal编程技术网

优化MySQL查询性能

优化MySQL查询性能,mysql,sql,indexing,query-performance,Mysql,Sql,Indexing,Query Performance,我的解决方案: 在@Alex的帮助下 我在表中添加了3个新列,分别命名为年(YYYY)、月(YYYY-MM)和日(YYYY-MM-DD),并在表中添加了3个索引: alter table vaadin_table add index (year, status); alter table vaadin_table add index (month, status); alter table vaadin_table add index (day, status); 现在我的问题是: selec

我的解决方案: 在@Alex的帮助下

我在表中添加了3个新列,分别命名为年(YYYY)、月(YYYY-MM)和日(YYYY-MM-DD),并在表中添加了3个索引:

alter table vaadin_table add index (year, status);
alter table vaadin_table add index (month, status);
alter table vaadin_table add index (day, status);
现在我的问题是:

select year,status, count(1) from vaadin_table group by year, status;
select month,status, count(1) from vaadin_table group by month, status;
select day,status, count(1) from vaadin_table group by day, status;
我可以在2秒钟内得到结果!谢谢你的帮助,非常感谢! Mysql似乎不支持索引列上的函数,这使得我原来的post查询无法工作

编辑: 谢谢你的回复

让我的问题更清楚。我需要从表中获取每日/每月/每年的统计数据

因此,我使用以下方法按日/月/年数据顺序进行分组:

子字符串(输入日期,1,11)--->YYYY-MM-DD

子字符串(输入日期,1,7)--->YYYY-MM

子字符串(输入日期,1,4)--->YYYY

所有这三列使我的查询速度变慢

原始问题: 我有一张270万行的表格。它包含3列:名称、状态和输入日期(YYYY-MM-DD HH:MM:SS)

我的目的是获取每个状态的每日数量:

SELECT substring(entry_date, 1, 11), status, count(1) 
FROM test_table 
GROUP BY
substring(entry_date, 1, 11), status;
它工作正常,但返回结果大约需要10秒

为了优化它,我将索引添加到表中,如下所示:

ALTER table test_table ADD INDEX test_index(entry_date, status);
我在网上看到了一些类似的问题,都建议根据分组顺序添加索引。但这对我的案子没有帮助。是因为我使用了entry\u date的子字符串吗

请帮忙,谢谢

SELECT entry_date, status, count(1) 
FROM test_table 
GROUP BY
DATE(entry_date), status;
或者更好地使用
DATE
类型添加额外的列

ALTER TABLE test_table ADD COLUMN entry_date1 DATE;
UPDATE test_table  SET entry_date1=DATE(entry_date);

SELECT entry_date1, status, count(1) 
FROM test_table 
GROUP BY
entry_date1, status;

为了优化它,我的建议如下

更改查询

SELECT date(entry_date), status, count(1) 
FROM test_table 
GROUP BY
status,date(entry_date);
然后按以下列顺序创建索引

ALTER table test_table ADD INDEX test_index( status,entry_date);

您的输入日期是日期-时间值为什么您在其上执行子字符串会降低性能?为什么
子字符串(输入日期,1,11)
,而不仅仅是
输入日期
?您是正确的;对条件或分组中的索引字段使用任何函数都会导致忽略索引(对于该条件或分组)。不幸的是,这甚至包括使用CAST或其他日期函数来获取datetime字段的日期获取YYYY-MM-DD时忽略了HH:MM:SS partYep,在索引列上使用任何函数都会导致忽略索引。然后,它将在执行group BY时使用状态索引感谢您的回复。我更新了我的问题以使其更精确。您的更新不会改变任何内容。针对每条记录调用的任何函数都会破坏性能,并且不会使用任何关于如何解决此类情况的索引建议?非常感谢这就是为什么我回答你试过了吗?我正要发布类似的答案。亚历克斯的建议实际上是正确的。制作三个不同的列(根据需要),为它们编制索引,然后将它们与
where
子句一起使用。MySQL不支持基于函数的索引。(可能使用Oracle?)
ALTER table test_table ADD INDEX test_index( status,entry_date);