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) --內(nèi)部查詢
可以看到,內(nèi)部查詢沒有使用到外部查詢的結果
相關子查詢
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) 內(nèi)部查詢
內(nèi)部查詢使用到了外部查詢的結果
結論
內(nèi)部查詢使用到了外部查詢的結果(內(nèi)部查詢的條件中有用到外部查詢的表)就是相關子查詢
相關子查詢外部每查詢一次都會得到一個結果,再拿這個結果去執(zhí)行內(nèi)部查詢,內(nèi)部查詢執(zhí)行多次
不相關子查詢,內(nèi)部查詢的結果作為外部查詢的條件,內(nèi)部查詢只執(zhí)行一次