1. 程式人生 > >Mysql 組合索引 最左側原理

Mysql 組合索引 最左側原理

網上那麼多關於組合索引詳解 最左側原理 : 個人感覺99%都是講不清楚的廢話,看完 都不知道在講個jb
因此在此寫一下!
原理:你使用的sql能否用到組合索引?
結論:你建立的組合索引(a,b,c,d) 無論怎麼使用只要和a沒有組合(最左面的那個),那麼都沒有使用上索引!!!!!
下面是驗證:EXPLAIN 觀察 type 列 
相關連線:[https://www.jianshu.com/p/ea3fc71fdc45(https://www.jianshu.com/p/ea3fc71fdc45)
  select table_name,
  DATA_LENGTH as tablesData,
  INDEX_LENGTH as
indexData from information_schema.tables where table_schema='test' ORDER BY indexData desc; -- 索引 ON `index` (a, b, c); EXPLAIN SELECT * FROM `index` WHERE a='a';-- type=ref ref=const rows =1 true EXPLAIN SELECT * FROM `index` WHERE b='b'; -- type=ALL rows=3 false EXPLAIN SELECT
* FROM `index` WHERE c='c'; -- type=ALL rows=3 false EXPLAIN SELECT * FROM `index` WHERE a='a' AND b='b'; -- type=ref ref=const rows =1 true EXPLAIN SELECT * FROM `index` WHERE b='b' AND a='a';-- type=ref ref=const rows =1 true EXPLAIN SELECT * FROM `index
` WHERE a='a' AND c='c';-- type=ref ref=const rows =1 true EXPLAIN SELECT * FROM `index` WHERE c='c' AND a='a';-- type=ref ref=const rows =1 true EXPLAIN SELECT * FROM `index` WHERE c='c' AND b='b';-- type=ref ref=const rows =1 false EXPLAIN SELECT * FROM `index` WHERE b='b' AND c='c';-- type=ref ref=const rows =1 false EXPLAIN SELECT * FROM `index` WHERE a='a' AND b='b' AND c='c';-- type=ref ref=const rows =1 true EXPLAIN SELECT * FROM `index` WHERE a='a' AND c='c' AND b='b';-- type=ref ref=const rows =1 true EXPLAIN SELECT * FROM `index` WHERE b='b' AND c='c' AND a='a';-- type=ref ref=const rows =1 true EXPLAIN SELECT * FROM `index` WHERE b='b' AND a='a' AND c='c';-- type=ref ref=const rows =1 true EXPLAIN SELECT * FROM `index` WHERE c='c' AND b='b' AND a='a';-- type=ref ref=const rows =1 true EXPLAIN SELECT * FROM `index` WHERE c='c' AND a='a' AND b='b';-- type=ref ref=const rows =1 true