想象我有兩個表:我怎樣才能找到客戶與數據庫中沒有訂單?
客戶(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
想象我有兩個表:我怎樣才能找到客戶與數據庫中沒有訂單?
客戶(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);
另一種選擇是左連接/ 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的各種選擇和相對優勢進行了深入的討論。
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;
嘗試在可能的情況下避免子查詢 - 它們可能會造成可怕的性能下降。
這並不困難,並且可以經由一個'左join'來完成。 [你嘗試過什麼?](http://whathaveyoutried.com) – 2013-05-01 11:25:53
選擇CUST_ID其中ORDER_ID> 1 – 2013-05-01 11:26:29