开发者

how should I index the tables corresponding to this query?

开发者 https://www.devze.com 2023-04-01 12:19 出处:网络
So I have the following query: SELECT d.iID1 as \'id\', SUM(d.sum + d.count*r.lp开发者_开发技巧)/sum(d.count) AS avgrat

So I have the following query:

SELECT d.iID1 as 'id',
                      SUM(d.sum + d.count*r.lp开发者_开发技巧)/sum(d.count) AS avgrat
                      FROM abce r, abcf d
                      WHERE r.aID = 1 AND
                      d.iID1 <> r.rID  AND d.iID2 = r.rID GROUP BY d.iID1
                      ORDER BY avgrat;

Table abcf currently has over 130217 rows and table abce currently has 5284 rows....this query is taking around 7 seconds to execute....

how should I put in indexes on the tables involved in this query in order to speed it up? What type of indexes should I put in and on which columns?

EXPLAIN output:

id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
 1, 'SIMPLE', 'd', 'ALL', '', '', '', '', 130217, 'Using temporary; Using filesort'
 1, 'SIMPLE', 'r', 'ALL', '', '', '', '', 5611, 'Using where; Using join buffer'


You have a bunch of aggregate functions and an order by clause.

1) I'd at least start with an index on d.iID2, r.rID from the d.iID2 =r.rID 2) an index on r.aID wouldn't hurt either...

Other than that, the aggregates, order by, and <> pretty much control the rest. Check the slow query log to see if this makes it in there as well. If this query is used alot, think about turning on caching and/or making it a stored procedure.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号