我正在努力处理我反复使用的查询类型的性能。任何帮助将不胜感激。
我有下表:
item week type flag value
1 1 5 0 0.93
1 1 12 1 0.58
1 1 12 0 0.92
1 2 6 0 0.47
1 2 5 0 0.71
1 2 5 1 0.22
... ... ... ... ...
(完整的表有大约10k个不同的项目,200周,1k类型。标志是0或1.总共大约20M行)
我想优化以下查询:
select item, week,
sum(value) as total_value,
sum(value * (1-least(flag, 1))) as unflagged_value
from test_table
where type in (5,10,14,22,114,116,121,123,124,2358,2363,2381)
group by item, week;
目前,我能得到的最快的是索引(类型,项目,周)和引擎= MyIsam。 (我在标准桌面上使用mysql。)
您有任何建议(指数,重新制定等)吗?
答案 0 :(得分:4)
根据我的知识GROUP BY
查询只能使用covering index.
在您的桌面上添加以下covering index
,然后选中EXPLAIN
:
ALTER TABLE test_table ADD KEY ix1 (type, item, week, value, flag);
在使用EXPLAIN
查询后添加索引检查:
SELECT type, item, week,
SUM(value) AS total_value,
SUM(IF(flag = 1, value, 0)) AS unflagged_value
FROM test_table
WHERE type IN(5,10,14,22,114,116,121,123,124,2358,2363,2381)
GROUP BY type, item, week;
您可能需要像这样修改您的查询:
SELECT item, week,
SUM(total_value) AS total_value,
SUM(unflagged_value) AS unflagged_value
FROM(
SELECT type, item, week,
SUM(value) AS total_value,
SUM(IF(flag = 1, value, 0)) AS unflagged_value
FROM test_table
GROUP BY type, item, week
)a
WHERE type IN(5,10,14,22,114,116,121,123,124,2358,2363,2381)
GROUP BY item, week;
查看查询执行计划。 SQLFIDDLE DEMO HERE
答案 1 :(得分:0)
我认为表格中只有两个索引
1. An index on type (non clustered)
2. A composite index on (item, week) in the same order (non clustered)