0

我正在为反复使用的查询类型的性能而苦苦挣扎。任何帮助将不胜感激。

我有下表:

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

您有什么建议(指数、重新表述等)吗?

4

2 回答 2

4

根据我的知识GROUP BY查询只能通过覆盖索引进行完全优化。

在您的桌子上添加以下内容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 演示在这里

于 2012-08-23T10:14:44.047 回答
0

我认为您应该在表中只有两个索引

1. An index on type (non clustered)
2. A composite index on (item, week) in the same order (non clustered)
于 2012-08-23T09:25:36.237 回答