分页查询优化
-
关联查询优化
嵌套循环连接算法(NLJ算法)
基于块的嵌套循环算法(BNL算法)
把驱动表的数据放到join buffer,把被驱动表中的数据拿出来和join buffer中的数据做对比,对于join buffer中不够存放驱动表中的所有数据,采取分段的策略进行存放。
为什么不使用索引的时候采用BNL算法
优化方式
尽量使用NLJ算法,即通过索引关联
让小表驱动大表(参与关联的数据集)
in:对于B表数据小于A表,in 优于exists
select * from A where id in (select * from B)=>for(id in select * from B){select * from A where A.id=B.id}
exists:对于A表数据小于B表,exists优于in
select * from A where exists (select 1 from B where A.id=B.id)=>for(select * from A ){select * from B where A.id=B.id}
count优化
字段有索引:count(*)=count(1)>count(字段)>count(主键):count(字段)是扫描二级索引
字段无索引:count(*)=count(1)>count(主键)>count(字段):count(字段)需要把字段的值拿出来放在内存,所以count(1)的效率更高
常见的优化方法
对于myisam引擎,会把总行数维护在磁盘上,innodb因为支持事务所以并没有这个存储值
- show table status like 表名可以获取到大概的估值
- 利用redis缓存记录
- 在mysql中专门维护一张表,使用本地事务
