首先有一张表
CREATE TABLE `v_app_version_log` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
`appid` int(10) NOT NULL DEFAULT '0' COMMENT '应用标识',
`version` varchar(10) DEFAULT NULL COMMENT '版本',
`version_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1已发布,0未发布',
`update_type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1强制更新,0非强制更新',
`app_url` varchar(255) DEFAULT NULL COMMENT '安装包下载地址',
`notice_num` int(10) NOT NULL DEFAULT '0' COMMENT '提醒量',
`download_num` int(10) NOT NULL DEFAULT '0' COMMENT '点击更新量',
`update_desc` varchar(500) DEFAULT NULL COMMENT '更新说明',
`app_sign_name` varchar(50) DEFAULT NULL COMMENT '包名',
`update_notice` int(10) NOT NULL DEFAULT '1' COMMENT '几天提醒一次',
`create_time` int(10) DEFAULT NULL COMMENT '创建时间',
`is_delete` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1已删除,0未删除',
`file_size` varchar(16) NOT NULL DEFAULT '' COMMENT '安装包文件大小,例如 30MB',
PRIMARY KEY (`id`),
KEY `appid` (`appid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=58 DEFAULT CHARSET=utf8 COMMENT='应用记录表'
插入一些数据:
INSERT INTO v_app_version_log (id, appid, version, version_status, update_type, app_url, notice_num, download_num, update_desc, app_sign_name, update_notice, create_time, is_delete, file_size) VALUES(3, 1000837638, 'V2.0.2', 1, 1, 'https://xxxx.apk', 999, 888, '修复列表BUG', 'com.lvyuanji.ptshop', 20, 1668408253, 1, '');
执行SQL语句:
SELECT
id as version_id,
`update_type`,
`update_desc`,
`create_time`,
`notice_num`,
`download_num`,
`version_status`,
`version`
FROM
`v_app_version_log`
WHERE
`appid` = 1000837637
AND `is_delete` = 0
ORDER BY
version desc
LIMIT 0, 10;
通过explain命令看到 Using filesort
然后我们新建一个索引:
CREATE INDEX v_app_version_log_appid_IDX USING BTREE ON v_app_version_log (appid,version);
再次通过explain命令看到已经没有 filesort了
然后我们通过OPTIMIZER_TRACE
SELECT * from information_schema.OPTIMIZER_TRACE ot ;
看到如下一段:
"index_order_summary": {
"table": "`v_app_version_log`",
"index_provides_order": true,
"order_direction": "desc",
"index": "v_app_version_log_appid_IDX",
"plan_changed": true,
"access_type": "ref"
} /* index_order_summary */
说明排序是使用了索引的。