我怎样才能更好地优化此查询?

时间:2015-02-02 21:57:59

标签: mysql sql query-optimization

这里的查询耗时超过20分钟。

SELECT * FROM company WHERE Age>5 GROUP BY Network ORDER BY Network DESC LIMIT 0,2001

我有Age和Network的索引。有没有办法更有效地运行此查询?使用服务器端语言(php)运行多个单独的查询是一种选择。

1 个答案:

答案 0 :(得分:0)

age, network, companyid上创建一个复合索引并测试其运行时间:

SELECT network, min(companyid)
FROM company
WHERE Age > 5
GROUP BY network;

这应该使用索引并且速度相当快。

现在,加入以获取其他信息:

select c.*
from company c join
     (SELECT network, min(companyid) as mincompanyid
      FROM company
      WHERE Age > 5
      GROUP BY network
      ORDER BY network DESC
      LIMIT 0, 2001
     ) n
     ON c.companyid = n.mincompanyid;

这假定company有一个名为companyid的主键和age, network, companyid上的综合索引。

编辑:

如果第一个查询相当快,那么估计获得2001非重复名称所需的行数。然后做:

select c.*
from company c join
     (SELECT network, min(companyid) as mincompanyid
      FROM (SELECT c.*
            FROM company
            WHERE Age > 5
            ORDER BY network DESC
            LIMIT 10000
           ) c
      GROUP BY network
      ORDER BY network DESC
      LIMIT 0, 2001
     ) n
     ON c.companyid = n.mincompanyid;

在这种情况下,假设10,000足够大,可以获得2,001个网络。此版本应解决性能问题。