mysql 优化(消除filesort)

针对select * from table where clo1> number order by clo2 desc。
其实按照常规的方法可以这样设计:key(clo1, clo2)
但是这种办法在mysql里不算是理想的,where条件里限定索引前部分是一个范围的情况下后面的order by还是会有filesort。如果where条件里限定索引前部分是一个常量,那么order by就会有效利用索引。例如:select * from table where clo1= number order by clo2 desc,explain的结果就不错。
为了让它能够利用上索引并且消除filesort,可以这样设计
索引:key(clo2,clo1);
select * from table where clo2> min_value and clo1> number order by clo2 desc;
这里where条件里同时执行了索引的两个列,并且为了保证逻辑一致,对clo2列的限定条件等效于无限定。

这样mysql就能很好的利用索引了。这个技巧在mysql high performance2里也有提过.


测试数据库

CREATE TABLE `test` (
  `id` int(10) NOT NULL auto_increment,
  `clo1` int(10) NOT NULL default '0',
  `clo2` int(10) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  KEY `cl21` (`clo2`,`clo1`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 ;


条件一
EXPLAIN SELECT * FROM account_list WHERE `clo1` >1 ORDER BY `clo2` DESC ;

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEaccount_listrangecl12cl124NULL80840Using where; Using index; Using filesort

条件二

EXPLAIN SELECT * FROM account_list WHERE `clo2` >0 AND `clo1` >1 ORDER BY `clo2` DESC ;

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEaccount_listrangecl21cl214NULL80840Using where; Using index


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值