Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize this MySQL query

This query was working fine when the database was small, but now that there are millions of rows in the database, I am realizing I should have looked at optimizing this earlier. It is looking at over 600,000 rows and is Using where; Using temporary; Using filesort (which leads to an execution time of 5-10 seconds). It is using an index on the field 'battle_type.'

SELECT username, SUM( outcome ) AS wins, COUNT( * ) - SUM( outcome ) AS losses
FROM tblBattleHistory
WHERE battle_type =  '0' && outcome <  '2'
GROUP BY username
ORDER BY wins DESC , losses ASC , username ASC 
LIMIT 0 , 50
like image 440
James Simpson Avatar asked May 27 '10 17:05

James Simpson


People also ask

What is MySQL optimization?

Optimization involves configuring, tuning, and measuring performance, at several levels. Depending on your job role (developer, DBA, or a combination of both), you might optimize at the level of individual SQL statements, entire applications, a single database server, or multiple networked database servers.


1 Answers

It appears you need an index on username, battle_type, outcome or username, outcome, battle_type.

like image 195
Gilbert Le Blanc Avatar answered Sep 18 '22 06:09

Gilbert Le Blanc