2013-05-01 4 views
-3

Представьте У меня есть две таблицы:Как я могу найти клиентов без заказов в базе данных?

клиентов (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 
+0

Это не сложно и может быть выполнено с помощью 'left join'. [Что вы пробовали?] (Http://whathaveyoutried.com) – 2013-05-01 11:25:53

+0

Выберите cust_id, где order_id> 1 –

ответ

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; 

НЕ иногда предлагается также как решение

select c.cust_id 
from customers c 
where c.cust_id NOT IN (select distinct customer_id from orders); 

Check here для углубленного обсуждения различных вариантов и относительных преимуществ.

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; 
1

Вы выбираете все строки из таблицы клиентов, где ID не отображается в таблице заказов

select * FROM customers where cust_id NOT IN 
    (select customer_id FROM orders) 
1
SELECT a.* 
FROM Customers a 
     LEFT JOIN Orders b 
      ON a.Cust_ID = b.Customer_ID 
WHERE b.Customer_ID IS NULL 
1

Попробуйте

select * from customers where cust_id not in (select distinct customer_id from orders) 
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; 

пытаются избегайте подзапросов, где это возможно - они могут быть ужасным хитом производительности.

Смежные вопросы