mysql普通索引和聯合索引測試
阿新 • • 發佈:2018-11-21
索引就用空間來換取時間
explain學習和引數代表的意思請參考 https://blog.csdn.net/ywdhzxf/article/details/84316712
下面我會用explain 來測試聯合索引和普通索引的作用項, 只測兩個欄位, source和name
有興趣的可以看下我下面的測試, 並不繁瑣, 沒興趣的直接看結論吧
1 聯合索引的第一個欄位可以當普通索引來用(沒有普通索引快, 但確實可以提高查詢效率, 可以看下面只有聯合索引的測試結果), 即比如我的聯合索引是name+source, 那麼我只拿name當where當條件也會命中索引, 但是用source就不會了, 查詢全部的資料;
2 如果只是兩個欄位聯合查詢的話, 兩個欄位單個查詢的次數也比較高, 那麼就不如直接建立兩個普通索引了(我的測試用的都是等於, 如果有其他條件的命中rows較多的話還是建議聯合索引, 畢竟聯合索引的type優先順序較高);
3 如果幾個欄位經常聯合查詢的話, 很有必要建一個聯合索引, 但可以把某個單個查詢應用較高的欄位放在第一位, 這樣也比較省索引了;
4 相同rows的情況下, type的優先順序越高(type的優先順序檢視explain學習那篇), 查的越快;
做的簡單測試, 如果不對請大神評論指導, 謝謝.
聯合索引(name+source), 普通索引(source, name)
select * from db where source=1 and name=1
explain 測試:
三個索引全部命中
type ref
rows 21行
select * from db where name=1
eplain 測試:
命中兩個索引
type ref
rows 30行
聯合索引(name+source)
select * from db where source=1 and name=1 explain 測試: 聯合索引命中 type ref rows 21行 select * from db where name=1 eplain 測試: 命中索引 type ref rows 30行 select * from db where source=1 explain 測試: 沒有命中索引 type all rows 10W+(所有的資料)
普通索引(source, name)
select * from db where source=1 and name=1
explain 測試:
命中兩個索引
type index_merge
rows 2
select * from db where name=1
eplain 測試:
命中索引
type ref
rows 30