想象我有两个表:我怎样才能找到客户与数据库中没有订单?
客户(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