mysql JOIN优化 清除filesort

性能优化

(1)显示inner join 和 隐式inner join

显示 --> select * from A inner join B on A.mobile = B.mobile;

隐式 --> select * from A inner join B where A.mobile = B.mobile;

10万数据的查询用时几乎相等。

(2)left join / right join 和 inner join

尽量用inner join 避免 外联结 和 null

在使用外联结的时候,如 -> select * from A left join B on A.mobile = B.mobile where whereCondition;

如果B中没有满足on condition的条件,则会产生一行所有列为null的数据。

  在 on condition 匹配阶段,where 条件不会被使用。在on condition结束后,where将会被使用,where条件将会从满足on condition的数据中再检索一次。

所以,在使用外联结市,我们要尽量给出尽可能多的匹配满足条件(即 on condition),减少where字句的检索。

不建议sql -> select * from A 

          left join B on A.mobile = B.mobile

          left join C on A.name = C.name

          where A.status = 1 and C.status = 1

建议的sql -> select * from A

          left join B on A.mobile = B.mobile and A.status = 1

          left join C on A.name = C.name and C.status = 1

尽量满足on condition,而少使用where的条件。

(3)on 条件 和 where 条件的不同

->select * from A left join B on A.mobile = B.mobile on A.name is not null;

将会返回A表的所有记录 和 B表中满足 (A.mobile = B.mobile on A.name is not null) 的记录;

->select * from A left join B on A.mobile = B.mobile where A.name is not null;

将会返回A表中所有记录 和 B表中满足 (A.mobile = B.mobile)的记录,然后 再通过where条件(A.name is not null)对结果进行筛选。

第一条sql语句返回的结果集条数 >= 第二条sql

(4)尽量避免子查询,而用join

(5)驱动表问题

驱动表定义:执行计划第一行为驱动表

join mysql会自动选择 最少行的表做驱动表;

left join 左边的作为驱动表,尽力用小表驱动大表

不管是你oracle,还是 MySQL,优化的目标是尽可能减少JOIN中Nested Loop的循环次数。

多表关联请尽量使用驱动表或者结束表做order by 这样可以不适用nested loop 做排序,消除filesort、temporary

更多情况会陆续更新

如「STRAIGHT_JOIN」强制连接顺序技巧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值