2 つのテーブルがあるとします。
顧客 (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);
もう 1 つのオプションは、LEFT 結合/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);
さまざまなオプションと相対的な強みに関する詳細な説明については、こちらをご覧ください。
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;
可能であればサブクエリを避けるようにしてください - それらはひどいパフォーマンスヒットになる可能性があります.