exists和not exists关键字

时间:2021-06-28 03:51:53

表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 EXIST (SELECT * FROM B WHERE A.ID=B.AID)

等价于 select id.name from A where A.ID IN (SELECT B.ID FROM B)
执行结果为
1 A1
2 A2

 

NOT EXISTS 就是反过来
SELECT ID,NAME FROM A WHERE NOT EXIST (SELECT * FROM B WHERE A.ID=B.AID)
执行结果为
3 A3