6.优化案例
类别:单表优化、多表优化
(1)单表优化
create table book(
bid int(4) primary key,
name varchar(20) not null,
authorid int(4) not null,
typeid int(4) not null
);
问题:查询authorid=1 且 typeid 为2或3的bid ?
1. 初始SQL(范围查询有时候会出现索引失效,因此放在最后)
select bid from book where authorid = 1 and typeid in(2, 3)
2. 优化:加索引
alter table book add index idx_tab(bid, authorid, typeid)
3. 根据查询顺序,调整索引顺序。
alter table book add index idx_tab(authorid , typeid, bid)
小结:a. 索引的定义和使用顺序一致
b. 索引需要逐步优化
c. 将含有In范围查询 放到where条件的最后,防止失效
(2)多表优化
create table teacher2(
tid int(4) primary key,
cid int(4) not null
)
create table course2(
cid int(4),
cname varchar(20)
);
问题:查询课程为java的老师?
1. 左连接 :
select * from teacher2 t left outer join course2 c on t.id=c.id where c.cname-'java'。
2. 小表驱动大表,比如小表数据量为10,而大表数据量为100,因此
...on t.id (10条数据)= c.id(100条数据)
3. 索引建立在经常查询的字段上, t.cid经常使用,且左连接应该为左表加索引。
总结:a.小表驱动大表 b. 索引建立在经常查询的字段上