WHERE expression IN (subquery)express
右邊圓括號內是返回一個字段的子查詢結果集,左邊的表達式(或字段)對查詢結果每一行進行一次運算和比較,若是結果集中存在相等的行,則IN結果爲'TRUE',不然爲'FALSE';測試
WHERE expression NOT IN (subquery)spa
NOT IN與IN正相反,若是結果集中不存在相等的行結果爲'TRUE',不然爲'FALSE'。
code
測試表:blog
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中的行io
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的行class
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
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)
WHERE EXISTS (subquery)select
括號內一樣是一個子查詢,若是子查詢有返回結果,則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。