使用Order By,Group By和One Million行优化MySql

时间:2011-01-14 22:55:52

标签: mysql

TestAppData:
    instance_id INT
    product_id SMALLINT
    installation_id INT
    data_id SMALLINT
    data_value_str varchar(255)
    data_value_num INT
    时间戳
    索引(installation_id)
    索引(installation_id,data_value_num)

TestAppInstallations:
    product_id SMALLINT
    installation_id INT
    主要(product_id,installation_id)

   SELECT TestAppInstallations.installation_id, 
          TestAppData.data_value_num AS num1
     FROM TestAppData
LEFT JOIN TestAppInstallations ON TestAppInstallations.installation_id = TestAppData.installation_id
                              AND TestAppData.data_id =1
 GROUP BY TestAppInstallations.installation_id
 ORDER BY TestAppData.data_value_num DESC 
    LIMIT 0 , 20

解释输出

id  select_type  table  type  possible_keys  key  key_len  ref  rows  Extra  
------------------------------------------------------------------------------
1 SIMPLE TestAppData ALL NULL NULL NULL NULL 360000 Using temporary; Using filesort 
1 SIMPLE TestAppInstallations index NULL PRIMARY 6 NULL 20000 Using index 

用上面的表格,mysql查询和解释输出。查询速度非常慢,因为速度太慢,我没有让它完成。行数超过100万。

我在installation_id和data_id上尝试了索引,但这没有帮助。我承认我不太清楚我需要什么样的索引。

我能做些什么来使这个变得可行吗?

编辑:抱歉,1,000,000行,而不是表格。

1 个答案:

答案 0 :(得分:2)

我颠倒了JOIN顺序,查询闪电般快速。因此,不是将数据表连接到安装表,而是反过来。

SELECT TestAppInstallations.installation_id, TestAppData.data_value_num AS num1
FROM TestAppInstallations
LEFT JOIN TestAppData ON TestAppInstallations.installation_id = TestAppData.installation_id
AND TestAppData.data_id =1
GROUP BY TestAppInstallations.installation_id
ORDER BY TestAppData.data_value_num DESC 
LIMIT 0 , 20