在SQL中,EXISTS和IN都用于子查詢,但它們的用途和行為有所不同。
例如,以下查詢將返回所有具有至少一個訂單的客戶:
SELECT *
FROM customers
WHERE EXISTS (
SELECT *
FROM orders
WHERE orders.customer_id = customers.customer_id
);
例如,以下查詢將返回所有具有訂單的客戶,其中訂單狀態為’Completed’:
SELECT *
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM orders
WHERE order_status = 'Completed'
);
總結: