mysql 組合索引中對范圍的查詢


 

 

 

  

建立表:

CREATE TABLE `ygzt_test` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`a` int(11) NOT NULL,
`b` int(11) NOT NULL,
`c` int(11) NOT NULL,
`d` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `a` (`a`,`b`,`c`,`d`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='測試';

 

一、實驗一,無order by

 

首先加聯合索引a,b,c,d

explain select * from ygzt_test where a=1 and b=2 and c=3 and d=4

修改sql:

explain select * from ygzt_test where a>1 and b=2 and c=3 and d=4

type已經由ref降為index

 

修改索引b,c,d,a

explain select * from ygzt_test where a>1 and b=2 and c=3 and d=4

done

 

二、實驗二,order by

 

建立索引a,b

explain select * from ygzt_test where a>0 order by b

可以看到,a>0使用了索引,order by b 未使用

 

修改索引為b,a

explain select * from ygzt_test where a>0   order by b

 

where 與 order by 都無索引

想起此前order by+select *的問題

這個問題單獨拿出來實踐下:

修改索引為b

explain select * from ygzt_test order by b

缺點:未使用索引

 

explain select b from ygzt_test order by b

 缺點:只能返回b

 

explain select b,a from ygzt_test  order by b

缺點:未使用索引

 

explain select * from ygzt_test FORCE INDEX (b)  order by b

缺點:type也就是index級別

 

索引b,a

explain select b,a from ygzt_test  order by b

缺點:與強制索引同,只能達到index級別,還加大了索引建立的復雜度

 

結論:使用強制索引

 

結論:

1.單列索引中——<,<=,=,>,>=,between,like(右邊模糊)適用索引

2.索引中有范圍的,有序性失效,解決方案以實際為准

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM