1. EXISTS 操作符
在 where 子句的 查询条件中,exists 操作符,会在子查询有返回行时,返回true;不论返回几行。
因此,子查询中的查询字段仅写1就好;标准的写法:EXISTS (SELECT 1 FROM tbl WHERE condition)
2. not exists操作符
not exists与exists正好相反,如果子查询没有返回结果,为’TRUE’,否则’FALSE’
3. 例子
子查询返回多条时,可以在 where 子句中 用 IN,来匹配查询条件。
select id, name from user_info
WHERE
id NOT IN (
select id from vistor_info where amount > 100
);
【注】:NOT IN的效率非常低,如果可以的话建议使用NOT EXISTS。
查询 user_info 表,且user_info.id为(vistor_info表中存在的且是 vistor_info 表中amount>11的那些id)
SELECT
id,
name
FROM
user_info
WHERE
EXISTS
(
SELECT
1
FROM
vistor_info
WHERE
vistor_info.id=user_info.id=
AND amount>100 );
);
查询customer表,且user_info.id不在(vistor_info表中的且是vistor_info表中amount>11的那些id)
SELECT
id,
name
FROM
user_info
WHERE
NOT EXISTS
(
SELECT
1
FROM
vistor_info
WHERE
vistor_info.id=user_info.id
AND amount>100 );
);