MySql 小表驱动大表

在了解之前要先了解对应语法 in 与 exist。

IN:

select * from A where A.id in (select B.id from B)

in后的括号的表达式结果要求之输出一列字段。与之前的搜索字段匹配,匹配到相同则返回对应行。

mysql的执行顺序是先执行子查询,然后执行主查询,用子查询的结果按条匹配主查询。

 

EXIST:

select * from A where exists(select * from B where B.id= A.id)

exist后的括号里则无输出要求,exist判断后面的结果集中有没有行,有行则返回外层查询对应的行。

ps所以exist还可以这样写: 用常量替换* ,反正是判断有没有行,不需要实际传回的数据。

select * from A where exist(select 1 from B where B.id= A.id)

mysql的执行顺序是先执行主查询,将主查询的数据放在子查询中做条件验证。

 

大体看来貌似exist的执行效率比in低,但其实exists子查询在底层做了优化,会忽略select清单,也并不会对每条数据进行对比。

 

 

比如这里有两张表 

+--------+----------+
| A.id   | A.name   |       //500行
+--------+----------+
+--------+----------+
| B.id   | B.name   |    //5000行
+--------+----------+

在查询中最好使用小表驱动大表,因为在外层表循环内层的时候,会锁定外层表,如果大表在外,会锁定5k次 。

 

如果要求查询所有id相同的Aname 有两种查询方式

1.select A.name from A where A.id in(select B.id from B)

2.select A.name from A where exists(select 1 from B where A.id = B.id)

1.由B表驱动A表 会先执行子查询 大表驱动小表

2.由A表驱动B表 会先执行主查询 小表驱动大表

如果需求变为 查询所有id相同的Bname 

1.select B.name from B where B.id in(select A.id from B)

2.select B.name from B where exists(select 1 from A where A.id = B.id)

1.小表驱动大表

2.大表驱动小表

 

posted @ 2019-04-03 11:00  茶饭不撕  阅读(3287)  评论(3编辑  收藏  举报