优化MySQL查询性能

时间:2016-06-29 16:50:17

标签: 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);

现在我的疑问是:

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不支持索引列上的函数,这使得我的原始帖子查询无法正常工作

修改 感谢所有回复。

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

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

substring(entry_date,1,11)---> YYYY-MM-DD

substring(entry_date,1,7)---> YYYY-MM

substring(entry_date,1,4)---> YYYY

所有这三列都让我的查询变慢。

原始问题: 我有270万行表。它包含3列:name,status和entry_date(YYYY-MM-DD HH:MM:SS)

CREATE TABLE IF NOT EXISTS test_table 
(id integer not null auto_increment primary key, 
name char(20) not null, status char(20) not null, 
entry_date datetime default 0);

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

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_date的子串吗?

请帮忙,谢谢

2 个答案:

答案 0 :(得分:2)

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;

答案 1 :(得分:1)

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

更改查询

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);