SELECT
customer_id,
first_name,
last_name
sales.customers
WHERE
EXISTS (SELECT NULL)
ORDER BY
first_name,
last_name;
执行上面查询语句,得到以下结果:
在此示例中,子查询返回包含NULL的结果集,这也导致EXISTS运算符计算为TRUE。
1.2. EXISTS带有相关子查询示例
考虑以下customers和orders表,它们的结构如下所示:
以下示例查找已下过两个以上订单的所有客户:
SELECT
customer_id,
first_name,
last_name
sales.customers c
WHERE
EXISTS (
SELECT
COUNT (*)
sales.orders o
WHERE
customer_id = c.customer_id
GROUP BY
customer_id
HAVING
COUNT (*) > 2
ORDER BY
first_name,
last_name;
SELECT
sales.orders
WHERE
customer_id IN (
SELECT
customer_id
sales.customers
WHERE
city = 'San Jose'
ORDER BY
customer_id,
order_date;
以下语句使用返回相同结果的EXISTS运算符:
SELECT
sales.orders o
WHERE
EXISTS (
SELECT
customer_id
sales.customers c
WHERE
o.customer_id = c.customer_id
AND city = 'San Jose'
ORDER BY
o.customer_id,
order_date;