子查询学习(2)

exists和not exists关键字

exists操作符检查在子查询中是否存在满足条件的行。exists只返回true或false。

exists和关联子查询:
1、如果在子查询中存在满足条件的行:
如果能找到一行,对于这个子查询来说,不继续查找,exists返回true。
继续下一个子查询。

2、如果在子查询中不存在满足条件的行:
如果没有一行满足子查询条件,子查询的查询结果为空,exists返回false。
继续下一个子查询。

因为exists只返回true或false,所以在子查询中select后面只要写成select 1就行了。

表还是用http://www.live-in.org/archives/2114.html中的TEST_T表。

select * from test_t t1 where exists (select 1 from test_t t2 where t2.score < 60 and t1.id = t2.id);

ID NO T_NAME S_NAME SCORE
4 1 Peter 小A 59

1)从主查询里取出一行,到子查询查找满足score < 60 and t1.id = t2.id的行
2)子查询只要找到一条满足条件的行,exists返回true,输出主查询的这一行
3)如果子查询结果为空,exists返回false,则不输出主查询的这一行

not exists关键字
没有满足条件的行,返回true。
有满足条件的行,返回false。
如果子查询的结果都为空,那么会返回主查询的所有行。

select * from test_t t1 where not exists (select 1 from test_t t2 where t2.score < 90 and t1.id = t2.id);

ID NO T_NAME S_NAME SCORE
6 3 Tom 小C 99
2 2 Mary 李四 99
9 3 Tom Li 90