MySQL-索引优化篇(2)_使用索引扫描来优化排序
文章目錄
- 生猛干貨
- 官方文檔
- 使用索引掃描來優化排序
- 索引的列順序和Order By子句的順序完全一致
- 索引中所有列的方向(升序、降序)和 order by子句完全相同
- order by中的字段全部在關聯表中的第一張表中
- 搞定MySQL
生猛干貨
帶你搞定MySQL實戰,輕松對應海量業務處理及高并發需求,從容應對大場面試
官方文檔
https://dev.mysql.com/doc/
如果英文不好的話,可以參考 searchdoc 翻譯的中文版本
http://www.searchdoc.cn/rdbms/mysql/dev.mysql.com/doc/refman/5.7/en/index.com.coder114.cn.html
使用索引掃描來優化排序
存儲引擎: Innodb
重點: 優化排序 手段:利用索引
兩個思路: 1 通過排序操作 、 2 按照索引順序掃描數據
索引的列順序和Order By子句的順序完全一致
舉幾個例子
mysql> show create table rental \G; *************************** 1. row ***************************Table: rental Create Table: CREATE TABLE `rental` (`rental_id` int(11) NOT NULL AUTO_INCREMENT,`rental_date` datetime NOT NULL,`inventory_id` mediumint(8) unsigned NOT NULL,`customer_id` smallint(5) unsigned NOT NULL,`return_date` datetime DEFAULT NULL,`staff_id` tinyint(3) unsigned NOT NULL,`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY (`rental_id`),UNIQUE KEY `rental_date` (`rental_date`,`inventory_id`,`customer_id`),KEY `idx_fk_inventory_id` (`inventory_id`),KEY `idx_fk_customer_id` (`customer_id`),KEY `idx_fk_staff_id` (`staff_id`),CONSTRAINT `fk_rental_customer` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`customer_id`) ON UPDATE CASCADE,CONSTRAINT `fk_rental_inventory` FOREIGN KEY (`inventory_id`) REFERENCES `inventory` (`inventory_id`) ON UPDATE CASCADE,CONSTRAINT `fk_rental_staff` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`staff_id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=16050 DEFAULT CHARSET=utf8mb4 1 row in set (0.00 sec)ERROR: No query specifiedmysql> explain select * from rental where rental_date > '2005-01-01' order by rental_id \G *************************** 1. row ***************************id: 1select_type: SIMPLEtable: rentalpartitions: NULLtype: index ---------------> 索引 possible_keys: rental_datekey: PRIMARYkey_len: 4ref: NULLrows: 16008filtered: 50.00Extra: Using where 1 row in set, 1 warning (0.00 sec)mysql>using where:表示優化器需要通過索引回表查詢數據;
select * , 除了索引列,其他的字段都需要回表來獲取,所以 是using where .
5.7.29 版本的mysql的存儲引擎是 Innodb,對于Innodb來講,邏輯順序和主鍵順序是一致的,所以可以利用主鍵來排序 ,上面 order by rental_id 就是利用主鍵來排序 。 看下 type: index
索引中所有列的方向(升序、降序)和 order by子句完全相同
我們知道,字段的默認是 ase 升序排列的。 如果order by 都使用升序的
using index condition:5.6加入 ,會先條件過濾索引,過濾完索引后找到所有符合索引條件的數據行,隨后用 WHERE 子句中的其他條件去過濾這些數據行;
但是如果 order by inventory_id desc, customer_id 的話, Extra中出現了 Using filesort ,這說明了啥?
在使用order by關鍵字的時候,如果待排序的內容不能由所使用的索引直接完成排序的話,那么MySQL有可能就要進行“文件排序” 【其實并不是從文件中查找排序,不要誤解】。
看下索引情況
最左側的索引 rental_date 使用范圍查詢 來驗證下
結論: 如果查詢中有某個列的范圍查詢,則其右邊所有列都無法使用索引
order by中的字段全部在關聯表中的第一張表中
搞定MySQL
總結
以上是生活随笔為你收集整理的MySQL-索引优化篇(2)_使用索引扫描来优化排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL-索引优化篇(1)_安装演示库
- 下一篇: MySQL-索引优化篇(3)_利用索引优