一.IN && NOT IN
WHERE expression IN (subquery)
右边圆括号内是返回一个字段的子查询结果集,左边的表达式(或字段)对查询结果每一行进行一次运算和比较,如果结果集中存在相等的行,则IN结果为’TRUE’,否则为’FALSE’;
WHERE expression NOT IN (subquery)
NOT IN与IN正相反,如果结果集中不存在相等的行结果为’TRUE’,否则为’FALSE’。
测试表:
test=# /d tbl_test Table "public.tbl_test" Column | Type | Modifiers --------+---------+----------- f | integer | test=# /d tbl_insert Table "public.tbl_insert" Column | Type | Modifiers --------+-----------------------+----------- a | integer | b | integer | c | character varying(12) | test=# select * from tbl_test ; f --- 1 3 5 (3 rows) test=# select * from tbl_insert; a | b | c ---+---+------- 1 | 1 | 11 2 | 2 | 22 3 | 3 | 33 4 | 4 | 44 5 | 5 | 51 6 | 6 | 1 6 | 6 | 61 6 | 6 | 661 7 | 7 | 3%1 8 | 8 | 3%_1 8 | 8 | 3_%_1 7 | 7 | abc 7 | 7 | ABc 7 | 7 | aBC (14 rows)
示例1.查询tbl_insert表,且a字段值在tbl_test表字段f中的行
test=# select * from tbl_insert where a in (select f from tbl_test); a | b | c ---+---+---- 1 | 1 | 11 3 | 3 | 33 5 | 5 | 51 (3 rows)
示例2.查询tbl_insert表,且a字段值比tbl_test表字段f小1的行
test=# select * from tbl_insert where a+1 in (select f from tbl_test); a | b | c ---+---+---- 2 | 2 | 22 4 | 4 | 44 (2 rows)
示例3.查询tbl_insert表,且a字段值不在tbl_test表字段f中的行
test=# select * from tbl_insert where a not in (select f from tbl_test); a | b | c ---+---+------- 2 | 2 | 22 4 | 4 | 44 6 | 6 | 1 6 | 6 | 61 6 | 6 | 661 7 | 7 | 3%1 8 | 8 | 3%_1 8 | 8 | 3_%_1 7 | 7 | abc 7 | 7 | ABc 7 | 7 | aBC (11 rows)
示例4.查询tbl_insert表,且a字段值等于5或7的行
test=# select * from tbl_insert where a in (5,7); a | b | c ---+---+----- 5 | 5 | 51 7 | 7 | 3%1 7 | 7 | abc 7 | 7 | ABc 7 | 7 | aBC (5 rows)
二.EXISTS && NOT EXISTS
WHERE EXISTS (subquery)
括号内同样是一个子查询,如果子查询有返回结果,则EXISTS结果为’TRUE’,否则为’FALSE’。
WHERE NOT EXISTS(subquery)
NOT EXISTS与EXISTS正好相反,如果子查询没有返回结果,为’TRUE’,否则’FALSE’。
示例1.查询tbl_insert表,且a字段值在tbl_test表字段f中的行
test=# select * from tbl_insert where exists (select null from tbl_test where tbl_test.f=tbl_insert.a); a | b | c ---+---+---- 1 | 1 | 11 3 | 3 | 33 5 | 5 | 51 (3 rows)
示例2.查询tbl_insert表,且a字段值不在tbl_test表字段f中的行
test=# select * from tbl_insert where not exists (select null from tbl_test where tbl_test.f=tbl_insert.a); a | b | c ---+---+------- 2 | 2 | 22 4 | 4 | 44 6 | 6 | 1 6 | 6 | 61 6 | 6 | 661 7 | 7 | 3%1 8 | 8 | 3%_1 8 | 8 | 3_%_1 7 | 7 | abc 7 | 7 | ABc 7 | 7 | aBC (11 rows)
PS:NOT IN的效率非常低,如果可以的话建议使用NOT EXISTS。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/4875.html