條件中有or
- 如果條件中有or,其中一個字段是索引字段,另一個是非索引字段,此時索引不會被使用,全表掃描。
- 如果條件中有or,左右是兩個不同的獨立索引字段,此時兩個索引字段都會用。
但其實完全可以用union來代替:
select * from xd_student where id = 2
union
select * from xd_student where room = 401
- 如果條件中有or,用的都是同一個索引字段,索引有用。
但其實完全可以用in來代替or:
select * from xd_student where id in (2,4);
使用like
如果以%開頭,索引不能用;以%結束,索引能用但是不用。
列類型是字符串,沒有使用引號
只有加鏈引號纔會用索引。
索引字段表達式
【補充】
查看索引的使用情況
show status like ‘Handler_read%’;
handler_read_key:這個值越大說明使用索引查詢到的次數越多
handler_read_rnd_next:這個值越高,說明查詢低效