mySql單列索引與聯合索引的區別


引自https://my.oschina.net/857359351/blog/658668

   第一張表gift和索引為聯合索引,如圖:

第二張表gift2為單列索引,如圖:

下面開始進行測試:

相同的SQL分別查詢兩張表,使用EXPLAIN解析一下SQL 

  select * from gift  where name = '道具' and scene_type=1;  

  select * from gift2 where name=‘道具’ and scene_type=1;

     顯示的結果為兩條SQL都會使用到索引,這我就不上圖了。

然后只查詢其中的某列,但是這個列已經創建索引 

  select name,status from gift  where name = '道具' and scene_type=1; 

  select name,status from gift2 where name=‘道具’ and scene_type=1;

    顯示的結果為兩條SQL也都使用了索引。

繼續查詢沒有創建索引的列,這里rank字段並沒有創建索引 

  select name,status,rank from gift  where name = '道具' and scene_type=1; 

  select name,status,rank from gift2 where name=‘道具’ and scene_type=1;

     顯示的結果為兩條SQL也都使用了索引。

接下來把SQL調整一下,name字段都建立了索引,下面把where條件里的name條件去掉 

  select name,status from gift  where scene_type=1; 

  select name,status from gift2 where scene_type=1;

     顯示的結果為兩條SQL也都使用了索引。

  select name,status,rank from gift  where scene_type=1;

  select name,status,rank from gift2 where scene_type=1;

   第一條SQL根本沒有用到索引,第二條SQL還和以前一樣,同樣使用到了索引。

  其實在聯合索引上會有一個mysql索引最左匹配原則,但是如果聯合索引的第一個列不在where條件語句中,並且所查詢的列其中有的是沒有建立索引的,那么這個聯合索引就是無效的,具體為什么會這樣我也還沒有整明白(囧),不過以后再寫SQL也會注意一下這方面的問題,而且公司DBA也建議如果使用聯合索引,那么where條件也要盡量根據聯合索引的順序來,如果不按照順序來,索引也同樣會用到,但是在執行前,SQL優化器也會將條件調整為聯合索引的順序,既然可以直接避免這種情況,就沒必要再讓SQL優化器去處理,畢竟處理也是有開銷的。


免責聲明!

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



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