如何在数据库中找到没有订单的客户?

时间:2013-05-01 11:24:21

标签: mysql sql

想象一下,我有两张桌子:

客户(的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

6 个答案:

答案 0 :(得分: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);

Check here深入讨论各种选项和相对优势。

答案 1 :(得分:1)

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;

答案 2 :(得分:1)

您可以从customers表中选择ID未出现在订单表

中的所有行
select * FROM customers where cust_id NOT IN 
   (select customer_id FROM orders)

答案 3 :(得分:1)

SELECT  a.*
FROM    Customers a
        LEFT JOIN Orders b
            ON a.Cust_ID = b.Customer_ID
WHERE   b.Customer_ID IS NULL

答案 4 :(得分:1)

试试这个

select * from customers where cust_id not in (select distinct customer_id from orders)

答案 5 :(得分:1)

select c.cust_id
from customers c
left join orders o on o.customer_id = c.cust_id
where o.customer_id is null;

尝试尽可能避免子查询 - 它们可能会造成严重的性能损失。