2013-05-01 2 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

이것은 어렵지 않으며 '왼쪽 결합'을 통해 수행 할 수 있습니다. [무엇을 시도 했습니까?] (http://whathaveyoutried.com) –

+0

cust_id를 선택하십시오. order_id> 1 –

답변

4

일반적으로는 상관 하위 쿼리는 때때로 NOT IN 조합/NULL NOT

select cust_id 
from customers 
where not exists (select * from orders 
        where orders.customer_id = customers.cust_id); 

또 다른 옵션은 남아있는 최선의 가입

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; 

가하려고 시도 가능한 경우 하위 쿼리를 피하십시오 - 성능이 크게 떨어질 수 있습니다.

관련 문제