Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL sum query taking huge time to complete. Looking for a bottleneck

I am running a simple MySQL query to find total time user spent playing the game:

SELECT userId, SUM(time) AS totalGameTime
                    FROM game_attempts
                    WHERE userId = 19599

EXPLAIN shows the following:

id  select_type  table  type  possible_keys  key  key_len  ref  rows  Extra
1  SIMPLE  game_attempts  ref  userId_gameId  userId_gameId  4  const  26880  

PROFILER shows, that most of the time spent on "Sending data":

Sending data    1.786524

Why such a simple query takes so much time to complete? Where to look for a bottleneck?

UPDATE. Time is INT(11) field, no conversions involved.

UPDATE. Possible solution is to introduce (userId, time) index, which solves the problem by moving part of the data to index-tree. But it doesn't solve the bigger problem of why summing up 30000 integers takes so long.

This question doesn't have a simple answer. Indices are right, no time-consuming conversions are involved. It's just about DB eninge tuning — why locating those 30000 records and retrieving data takes so much time?

Important to say that table using InnoDB engine and conains about 2 million records.

like image 475
Denis Kulagin Avatar asked Nov 03 '22 17:11

Denis Kulagin


1 Answers

try making an index to userId like this will solve your problem:

   ALTER TABLE game_attempts ADD INDEX (userId);
like image 166
echo_Me Avatar answered Nov 15 '22 06:11

echo_Me