繁体   English   中英

优化MySQL查询性能

[英]Optimize MySQL query performance

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

我在表中添加了3个新列,将它们命名为year(YYYY),month(YYYY-MM)和day(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

所有这3列都使我的查询变慢。

原问:我有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的子串吗?

请帮忙,谢谢

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

暂无
暂无

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

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