Mysql 优化

1 小表驱动大表

使用in的sql:select * from A where id in (select id from B)
等价于:
for select id from B
for select * from A where A.id = B.id
当B表的数据小于A表的数据集时,用in
使用exists的sql:select * from A where exists (select 1 from B where B.id=A.id)
等价于:
for select id from A
for select * from B where B.id = A.id
当A表的数据小于B表的数据集时,用exists

EXISTS:
selectfrom table where exists (subquery)可以理解为:将主查询的数据。放到子查询中做条件验证,根据验证结果(true or false)来决定主查询的数据是否得以保留
提示:
1.exists(subquery)只返回true或者false,因此子查询的select *可以使select 1或其他,实际执行时候会忽略掉select清单,因此没有区别
2.exists子查询的实际执行过程可能经历了优化而不是我们理解上的逐条对比,如果担忧效率问题,可进行实际检验以确认效率是否有问题
3.exists子查询往往也可以用条件表达式、其他子查询或者join来代替

原文地址:https://www.cnblogs.com/woshuaile/p/12017829.html