在mysql中,索引可以有效的提高查詢效率,但在實際項目中有時候即使在where條件都加上索引,也不一定能夠使用到索引,更多情況下是聯合索引用的比較多
舉個栗子:where id=3 and price>100;//查詢id為3,100元以上的商品(id,price 分別為添加索引)
誤區:只能用上id或price其中一個,因為是獨立的索引,同時只能用上一個。
聯合索引:在多列同時創建索引后,需要滿足左前綴原則,才用到索引
以index(a,b,c)為例。(注意和順序有關)
語句 | 是否使用索引 |
where a=3 | 是,只使用了a列 |
where a=3 and =5 | 是,使用了ab列 |
where a=3 and b=4 and c=5 | 是,使用了abc |
where b=3 or c=4 | 否因為跳過a |
where a=3 and c =4 | a用到索引,c不能 |
where a=3 and b like 'hello%' | a用到了,b部分用到 |