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) --內(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í)行一次

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容