想象一下我有两张桌子:
客户(cust_id) 订单(order_id,cust_id)
如何获取所有没有订单的客户?
示例数据库:
customers
cust_id
1
2
3
4
orders
order_id customer_id
1 1
2 2
3 3
4 3
So what I want to retrieve is:
cust_id
4
通常,相关子查询会执行得最好
select cust_id
from customers
where not exists (select * from orders
where orders.customer_id = customers.cust_id);
另一个选项是 LEFT join/NOT NULL 组合
select c.cust_id
from customers c
left join orders o on o.customer_id = c.cust_id
where o.customer_id is null;
NOT IN 有时也作为解决方案提供
select c.cust_id
from customers c
where c.cust_id NOT IN (select distinct customer_id from orders);
在这里查看对各种选项和相对优势的深入讨论。
SELECT c.cust_id
FROM customers AS c
LEFT JOIN orders AS o
ON c.cust_id=o.customer_id
WHERE o.customer_id IS NULL;
您从客户表中选择 ID 未出现在订单表中的所有行
select * FROM customers where cust_id NOT IN
(select customer_id FROM orders)
SELECT a.*
FROM Customers a
LEFT JOIN Orders b
ON a.Cust_ID = b.Customer_ID
WHERE b.Customer_ID IS NULL
试试这个
select * from customers where cust_id not in (select distinct customer_id from orders)
select c.cust_id
from customers c
left join orders o on o.customer_id = c.cust_id
where o.customer_id is null;
尽量避免子查询 - 它们可能会严重影响性能。