SQL exists簡析

前言

本文只是通過一個例子,得到我對SQL中exists的一個簡單理解,所以很短,有錯誤,望告知(●’◡’●)!

主體

用到的兩張表:
sc表:

sno cno grade
201215121 1 92
201215121 2 85
201215121 3 88
201215122 2 90
201215122 3 80

student表:

sno sname ssex sage
201215121 李勇 20
201215122 劉晨 19
201215123 王敏 18
201215124 張立 19

需求:
篩選出選擇了課程號爲2的學生姓名(即cno=2)
上代碼:

select sname
from student
where exists(
				select * from sc
				where cno=2 and sc.sno=student.sno
            )

分析執行過程:
1.從student表中的第一行數據開始,把數據中的sno傳遞給內查詢(因爲內查詢中需要該數據,內查詢指括號裏面的select語句)
2.則此時內查詢語句相當於變爲

select * from sc
where cno=2 and sc.sno='201215121'

3.若第二步中的查詢語句查詢到的結果不爲空,則內查詢返回ture,並將該行數據保存到結果集
4.對student表中每條數據由上到下進行以上步驟,最後形成最終的結果集,並輸出其中的sname
引申思考:
如果把上面代碼變爲:

select sname
from student
where exists(
				select * from sc,student
				where cno=2 and sc.sno=student.sno
            )

相比較與上述代碼,該代碼只是增加了一個student,大家可以思考下最後輸出結果會有什麼不同呢?爲什麼會這樣呢?(⊙_⊙)?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章