CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`user_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '員工id',
`create_date` datetime NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '創建日期',
省略其他字段
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`)
explain SELECT * FROM user ORDER BY create_date DESC limit 20.40;
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
| 1 | SIMPLE | user | ALL | NULL | NULL | NULL | NULL | 22686 | Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
-
對需要排序的記錄生成 <sort_key,rowid> 的元數據進行排序,該元數據僅包含排序字段和rowid。排序完成後只有按字段排序的rowid,因此還需要通過rowid進行回表操作獲取所需要的列的值,可能會導致大量的隨機IO讀消耗;
-
對需要排序的記錄生成 <sort_key,additional_fields> 的元數據,該元數據包含排序字段和需要返回的所有列。排序完後不需要回表,但是元數據要比第一種方法長得多,需要更多的空間用於排序。
查詢1:select * from user where user_id=1;
查詢2:select user_id,id from user where user_id=1;
explain SELECT create_date,id FROM user ORDER BY create_date DESC;
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
| 1 | SIMPLE | user | ALL | NULL | NULL | NULL | NULL | 22686 | Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
explain SELECT create_date,id FROM user ORDER BY create_date DESC;
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
| 1 | SIMPLE | user | ALL | NULL | NULL | NULL | NULL | 22686 | Using index |
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
explain SELECT create_date,user_id FROM user ORDER BY create_date DESC;
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
| 1 | SIMPLE | user | ALL | NULL | NULL | NULL | NULL | 22686 | Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+-------+----------------+
歡迎關注公衆號,讓我們一起學習探討問題