开发者

Slow mysql select

开发者 https://www.devze.com 2023-02-11 00:06 出处:网络
I have a table with the following structure: CREATE TABLE `game_entries` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT,

I have a table with the following structure:

CREATE TABLE `game_entries` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `player_id` int(11) unsigned NOT NULL,
  `game_id` int(11) unsigned NOT NULL,
  `hero_id` int(11) unsigned NOT NULL,
  `game_avg_pts` smallint(4) unsigned NOT NULL DEFAULT '0',
  `game_season` tinyint(2) unsigned NOT NULL,
  `game_length` smallint(11) unsigned NOT NULL,
  `game_mode` char(10) NOT NULL,
  `game_is_tb` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `game_map` char(10) NOT NULL,
  `game_date` datetime NOT NULL,
  `game_playersnum` tinyint(2) NOT NULL,
  `side` tinyint(2) unsigned NOT NULL,
  `won` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `pts` smallint(11) unsigned NOT NULL,
  `pts_change` smallint(4) NOT NULL,
  `kills` smallint(4) unsigned NOT NULL DEFAULT '0',
  `deaths` smallint(4) unsigned NOT NULL DEFAULT开发者_JAVA百科 '0',
  `assists` smallint(4) unsigned NOT NULL DEFAULT '0',
  `creeps` smallint(4) unsigned NOT NULL DEFAULT '0',
  `towers` tinyint(2) unsigned NOT NULL DEFAULT '0',
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `player_game` (`player_id`,`game_id`),
  KEY `index_game` (`game_id`),
  KEY `index_player` (`player_id`),
  KEY `index_hero` (`hero_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11706564 DEFAULT CHARSET=utf8;

The table has more than 11M rows. When I try to select all game_entries for a specific player_id, the query takes too long:

mysql> SELECT * FROM `game_entries` WHERE player_id = 4;
227 rows in set (1.68 sec)

mysql> SELECT * FROM `game_entries` WHERE player_id = 4 LIMIT 25;
25 rows in set (0.27 sec)

mysql> EXPLAIN SELECT * FROM `game_entries` WHERE player_id = 4;
+----+-------------+--------------+------+--------------------------+-------------+---------+-------+------+-------+
| id | select_type | table        | type | possible_keys            | key         | key_len | ref   | rows | Extra |
+----+-------------+--------------+------+--------------------------+-------------+---------+-------+------+-------+
|  1 | SIMPLE      | game_entries | ref  | player_game,index_player | player_game | 4       | const |  226 |       |
+----+-------------+--------------+------+--------------------------+-------------+---------+-------+------+-------+
1 row in set (0.00 sec)

Is there any way to improve the speed of this query?


One way is to add an index on player_id column.

Second, if possible, you can mention the limited fields in select query instead of *


Consider making {player_id, game_id} the primary key instead to take advantage of the "clustering" feature on innoDb primary key.

That would keep game records for the same player "near" each other and make searches on player_id = ? faster.

0

精彩评论

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