繁体   English   中英

MySQL在执行“ order by”时停留在“ using filesort”

[英]MySQL stuck on “using filesort” when doing an “order by”

我似乎无法让我的查询停止使用文件排序。

这是我的查询:

SELECT s.`pilot`, p.`name`, s.`sector`, s.`hull` 
FROM `pilots` p 
 LEFT JOIN `ships` s ON ( (s.`game` = p.`game`) 
  AND (s.`pilot` = p.`id`) ) 
WHERE p.`game` = 1 
 AND p.`id` <> 2 
 AND s.`sector` = 43 
 AND s.`hull` > 0 
ORDER BY p.`last_move` DESC

表结构:

CREATE TABLE IF NOT EXISTS `pilots` (
  `id` mediumint(5) unsigned NOT NULL AUTO_INCREMENT,
  `game` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `last_move` int(10) NOT NULL DEFAULT '0',
  UNIQUE KEY `id` (`id`),
  KEY `last_move` (`last_move`),
  KEY `game_id_lastmove` (`game`,`id`,`last_move`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;

CREATE TABLE IF NOT EXISTS `ships` (
  `id` mediumint(5) unsigned NOT NULL AUTO_INCREMENT,
  `game` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `pilot` mediumint(5) unsigned NOT NULL DEFAULT '0',
  `sector` smallint(5) unsigned NOT NULL DEFAULT '0',
  `hull` smallint(4) unsigned NOT NULL DEFAULT '50',
  UNIQUE KEY `id` (`id`),
  KEY `game` (`game`),
  KEY `pilot` (`pilot`),
  KEY `sector` (`sector`),
  KEY `hull` (`hull`),
  KEY `game_2` (`game`,`pilot`,`sector`,`hull`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;

解释:

id  select_type  table  type  possible_keys  key  key_len  ref  rows  Extra
1  SIMPLE     p  ref  id,game_id_lastmove  game_id_lastmove  1  const  7  Using where; Using filesort
1  SIMPLE     s  ref  game,pilot,sector...  game_2  6  const,fightclub_alpha.p.id,const  1    Using where; Using index

编辑:我从查询/表结构中删除了一些不必要的部分。

有人有什么想法吗?

最好的办法是建立索引:

  1. 涵盖具有以下字段的表格ships索引: game + pilot + sector + hull按此特定顺序
  2. pilotsgame + id

此特定查询将始终使用文件排序,因为它没有范围条件p.id <> 2

http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html

在某些情况下,MySQL无法使用索引来解析ORDER BY,尽管它仍然使用索引来查找与WHERE子句匹配的行。 这些情况包括以下情况:用于获取行的键与在ORDER BY中使用的键不同

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM