单表的索引
以下面的表为例,表叫article。
创建索引语句:
create index idx_ccv on article(category_id,comments,views);
查询语句:
explain select id,author_id from `article` where category_id=1 and comments>1 order by views desc limit 1;
explain的结果如下:
extra列出现了using filesort,全表扫描,说明索引跟没有上一样,并没有加快速度。原因是这样的,根据索引的创建顺序,我们先建立的是category_id,索引先按照有序的category_id查找,之后遇到了comments>1的range查询,在按照有序的comments查询的时候,无法再保证views是有序的,所以索引没发继续用,只能全表扫描。
两个表的索引
两个表结构class和book。
连接查询语句:
select * from book left join class on book.card=class.card;
首先一个问题就是,这个索引在calss表还是book表?
直接给出结论:
左连接索引建在left join右面的表,右连接索引在right join左面的表
以左连接为例:
创建索引:
create index idx on class(card);
左连接查询:
explain select * from book left join class on book.card=class.card;
explain结果:
对于左连接,左表必须全部查询,所以做表建索引没有意义,给右表建就可以了,右连接同理。
两个以上表的索引
在两个表的基础上又建立了一个phone表。
查询语句:
select * from class left join book on class.card=book.card left join phone on book.card=phone.card;
根据两个表的经验,可以推出应在leftjoin右边建索引,也就是book和phone上面对card列建立索引。
join的优化
- 用小的结果集驱动大的结果集。left join左边集合最好是小的。
- 优先优化内层循环。
- join的被驱动表要加上索引。