SQL Exists 的概念
Exists 概念總是模糊不清,記錄下來以供參考
Exists原理:exists做为where 候,是先對where 前的主查詢進行查詢,然後用主查询的結果一個一個的代入exists的查詢進行判斷,如果則輸出當前這一條出主查詢的結果,否則不輸出
例子:
表A
ID NAME
1 A1
2 A2
3 A3
表B
ID AID NAME
1 1 B1
2 2 B2
3 2 B3
SELECT ID , NAME FROM A WHERE EXISTS (SELECT * FROM B WHERE A.ID = B.AID)
結果為
1 A1
2 A2
可以按照如下分析
SELECT ID , NAME FROM A WHERE EXISTS (SELECT * FROM B WHERE B.AID = 1)
–>SELECT * FROM B WHERE B.AID = 1有值返回真所以有数据
SELECT ID , NAME FROM A WHERE EXISTS (SELECT * FROM B WHERE B.AID = 2)
–>SELECT * FROM B WHERE B.AID = 2有值返回真所以有数据
SELECT ID , NAME FROM A WHERE EXISTS (SELECT * FROM B WHERE B.AID = 3)
–>SELECT * FROM B WHERE B.AID = 3无值返回真所以没有数据
发表评论或回复