Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL:使用ORDER BY时避免文件排序_Mysql_Sql_Performance_Filesort - Fatal编程技术网

MySQL:使用ORDER BY时避免文件排序

MySQL:使用ORDER BY时避免文件排序,mysql,sql,performance,filesort,Mysql,Sql,Performance,Filesort,我得到了下一列的索引 CREATE TABLE table1 ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `kid` int(10) unsigned NOT NULL, `table_group` varchar(100) COLLATE utf8_bin NOT NULL) ENGINE=InnoDB; 该表有500万行与where子句匹配;当我对下面的查询进行解释时,它的doing filesort和运行时的limit需要10秒,这非常高

我得到了下一列的索引

    CREATE TABLE table1 (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`kid` int(10) unsigned NOT NULL,
`table_group` varchar(100) COLLATE utf8_bin NOT NULL)
ENGINE=InnoDB;
该表有500万行与where子句匹配;当我对下面的查询进行解释时,它的doing filesort和运行时的limit需要10秒,这非常高

PRIMARY KEY (`id`)
KEY `index1` (`kid`,`table_group`);

我想避免这种文件排序;请帮忙

不行。您正在使用一个
orderby
子句。db事先不知道将要找到多少条记录,因此它必须将结果缓存在临时文件中,以便进行排序/限制。您有1052764行符合条件,不适合内存。如果过滤效果更好,您可以将其删除。您可以在不使用文件排序的情况下获得有序的结果。你可以尝试删除你的
强制索引(index1)
,然后检查explain,看看mysql是否可以使用主键执行
排序。或者尝试将
id
添加到
index1
键中,为什么要强制这样的索引?试图超越规划师的工作?我们不知道索引中的值的分布。您不应该在生产中强制索引。
mysql> explain select * from db1.table1 FORCE INDEX(index1) where kid=187 and table_group in ('NOT_PRESENT', 'NOTHING', 'PERROR') order by id limit 200\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: tabl1
         type: range
possible_keys: index1
          key: index1
      key_len: 306
          ref: NULL
         rows: 1052764
        Extra: Using index condition; Using filesort