-3

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
4

6 に答える 6

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

さまざまなオプションと相対的な強みに関する詳細な説明については、こちらをご覧ください。

于 2013-05-01T11:25:25.133 に答える
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;
于 2013-05-01T11:26:23.917 に答える
1

注文テーブルに ID が表示されない顧客テーブルからすべての行を選択します。

select * FROM customers where cust_id NOT IN 
   (select customer_id FROM orders)
于 2013-05-01T11:26:27.177 に答える
1
SELECT  a.*
FROM    Customers a
        LEFT JOIN Orders b
            ON a.Cust_ID = b.Customer_ID
WHERE   b.Customer_ID IS NULL
于 2013-05-01T11:26:29.303 に答える
1

これを試して

select * from customers where cust_id not in (select distinct customer_id from orders)
于 2013-05-01T11:26:29.797 に答える
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;

可能であればサブクエリを避けるようにしてください - それらはひどいパフォーマンスヒットになる可能性があります.

于 2013-05-01T11:27:06.540 に答える