mysql相关查询和不相关查询

score表

20180701162643292.png

不相关子查询

select * from score as a where a.cou_id=1 and a.score>(select avg(b.score) from score as b where b.cou_id=1);

select * from score as a where a.cou_id=1 and a.score> --外部查询
(select avg(b.score) from score as b where b.cou_id=1) --内部查询
可以看到,内部查询没有使用到外部查询的结果

相关子查询

select * from score as a where a.score > 
(select avg(b.score) from score as b where a.cou_id=b.cou_id);

select * from score as a where a.score> --外部查询
(select avg(b.score) from score as b where a.cou_id=b.cou_id) 内部查询
内部查询使用到了外部查询的结果

结论

内部查询使用到了外部查询的结果(内部查询的条件中有用到外部查询的表)就是相关子查询
相关子查询外部每查询一次都会得到一个结果,再拿这个结果去执行内部查询,内部查询执行多次
不相关子查询,内部查询的结果作为外部查询的条件,内部查询只执行一次

你可能感兴趣的:(mysql相关查询和不相关查询)