这里的查询耗时超过20分钟。
SELECT * FROM company WHERE Age>5 GROUP BY Network ORDER BY Network DESC LIMIT 0,2001
我有Age和Network的索引。有没有办法更有效地运行此查询?使用服务器端语言(php)运行多个单独的查询是一种选择。
答案 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个网络。此版本应解决性能问题。