各位好:
在使用Mysql数据库查询数据时,使用order by进行排序,但是用explain时发现却没有走索引,不知道差哪了,麻烦各位帮忙指导下,谢谢!
CREATE TABLE `youhuer_share_record` (
`shareId` varchar(32) NOT NULL,
`userId` varchar(32) DEFAULT NULL,
`shareTime` int(10) DEFAULT NULL,
`status` int(1) DEFAULT NULL,
`businessId` varchar(32) DEFAULT NULL,
`businessType` int(1) DEFAULT NULL,
`title` varchar(1000) DEFAULT NULL,
`shareType` int(1) NOT NULL DEFAULT '0',
`des` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`shareId`),
KEY `idx_share_userId` (`userId`,`status`,`shareTime`) USING BTREE,
KEY `idx_share_shareTime` (`userId`,`shareTime`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
执行explain结果如下:
explain select shareId,userId,shareTime,status,businessId,businessType,title,shareType,des from youhuer_share_record where userId = '0' and status = 1 order by shareTime desc limit 1,5;
+----+-------------+----------------------+------+--------------------------------------+------+---------+------+------+-----------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------------+------+--------------------------------------+------+---------+------+------+-----------------------------+
| 1 | SIMPLE | youhuer_share_record | ALL | idx_share_userId,idx_share_shareTime | NULL | NULL | NULL | 4 | Using where; Using filesort |
+----+-------------+----------------------+------+--------------------------------------+------+---------+------+------+-----------------------------+
1 row in set
MySQL
这样建索引试试:`userId`,`status`这两列建复合索引,shareTime单独建索引。
order by userid,shareTime
因为是`userId`,`shareTime`组合索引,只可以从左边字段开始使用索引
order by userId,shareTime或order by userId可以用上索引
如果已经对索引做了优化,但是引擎没有走特定的索引 ,在这种情况下, 可以强制指定索引,就完事了!
索引不但需要最左匹配原则,还要离散性好,我估计你的status 里面基本是0,1这种重复数据
status = 1 order by shareTime +0 desc limit 1,5;
shareTime +0 就会走索引