exists和not 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 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

 

 

应用场景:

--不等于
select * from udf_user u where not exists (
        select * from armc_user_team t where t.user_name=u.username_ and t.team_code='DCCDJP'
        )
        
 --同时存在
 select * from armc_user_team t where t.team_code='a'
 and exists(select * from armc_user_team t1 where t1.user_name=t.user_name and t1.team_code='b')
 
        
 

 

posted @ 2019-04-24 16:24  第二人生Bonnie  阅读(1404)  评论(0编辑  收藏  举报