1.大多数情况,MySQL会将独立子查询转化为相关子查询,这样就影响了SQL执行效率。
select name from student where id in (select student_id from lesson );
select name from student where exists (select 1 from lesson where student.id = lesson.student_id);
如上,MySQL的优化器会将 in 的独立子查询优化为exists的相关子查询。执行效率变为O(N+M*N)而不是O(N+M)。我们可以具体优化相关子查询的参数条件来优化。
2.可以用explain 查看SQL具体的如何执行的参数,和具体如何执行的 explain extended详解 。
3.查看慢查询日志,查看物理IO 逻辑IO次数,top 10。
4.关联子查询优化,建唯一索引,使用派生表(避免相关子查询和外部查询的多次比较操作)。
select orderid,customerid,emploeeid,orderdate,requireddate from orders as a
where orderdate=(select max(orderdate) from orders as b where a.employeeid=b.employeeid);
建立索引
create unique indes idx_empid_od_rd_oid on orders(employeeid,orderdate,requireddate,orderid)
使用派生表
select a.orderid,a.customerid,a.employeeid,b.orderdate,requireddate from orders as a,
(select employeeid,max(orderdate) as orderdate from orderd group by employeeid) as b
where a.employeeid=b.employeeid and a.orderdate=b.orderdate;