exist和not exist用法
参考:http://wenku.baidu.com/view/577f4d49cf84b9d528ea7a6f.html //这个讲的很详细
引用自:http://chenling1018.blog.163.com/blog/static/14802542007112944944177/
--exists (sql 返回结果集,为真) --not exists (sql 不返回结果集,为真) --如下: --表A ID NAME A1 A2 A3 --表B ID AID NAME 1 B1 2 B2 2 B3 --表A和表B是1对多的关系 A.ID => B.AID SELECT ID,NAME FROM A WHERE EXIST (SELECT * FROM B WHERE A.ID=B.AID) --执行结果为 A1 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无值,返回假,所以没有数据 --NOT EXISTS 就是反过来 SELECT ID,NAME FROM A WHERE NOT EXIST (SELECT * FROM B WHERE A.ID=B.AID) --执行结果为 A3 =========================================================================== --EXISTS = IN,意思相同不过语法上有点点区别,好像使用IN效率要差点,应该是不会执行索引的原因 SELECT ID,NAME FROM A WHERE ID IN (SELECT AID FROM B) --NOT EXISTS = NOT IN ,意思相同不过语法上有点点区别 SELECT ID,NAME FROM A WHERE ID NOT IN (SELECT AID FROM B)