我的解决方案:与@Alex的帮助
我向表中添加了3个新列,将它们命名为年份(YYYY)、月份(YYYY)和日期(YYYY 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查询无法运行
编辑:,谢谢你的回复。
让我的问题更清楚。我需要从桌子上得到每日/每月/每年的统计数据。
因此,我使用下面的按日/月/年数据分组,以便:
子字符串(entry_date,1,11) --> YYYY-MM-DD
子字符串(entry_date,1,7) -->YYYY
子字符串(entry_date,1,4) --> YYYY
所有这3列都使我的查询变慢了。
原始问题:--我有一个270万行表。它包含3列:名称、状态和entry_date(YYYY: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的子字符串吗?
请帮忙,谢谢
发布于 2016-06-29 16:57:46
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;发布于 2016-06-29 16:58:17
为了优化它,我的建议如下
变更查询
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);https://stackoverflow.com/questions/38105707
复制相似问题