leetcode183 從不訂購的客戶 Customers Who Never Order

假設一個網站包含兩個表,Customers 表和 Orders 表。編寫一個SQL語句找出全部從不訂購任何東西的客戶。mysql

 

 建立表和數據:sql

Create table If Not Exists Customers (Idint, Name varchar(255));
Create table If Not Exists Orders (Id int,CustomerId int);
Truncate table Customers;
insert into Customers (Id, Name) values('1', 'Joe');
insert into Customers (Id, Name) values('2', 'Henry');
insert into Customers (Id, Name) values('3', 'Sam');
insert into Customers (Id, Name) values('4', 'Max');
Truncate table Orders;
insert into Orders (Id, CustomerId) values('1', '3');
insert into Orders (Id, CustomerId) values('2', '1');

解法:測試

1.顧客表的id和訂單表的customerid關聯,得出的是買了的東西的顧客。用left join,沒買東西的顧客,其對應的訂單爲空。這是一種求集合差的方法。網站

select C.name as Customers
from Customers as C left join Orders as O on (C.id = O.customerid)
where O.id is NULL;

先用子查詢將買過東西的顧客id選出來。 在應用left join求集合差。spa

select C.name as `Customers`
from Customers as C left join (
    select distinct customerid
    from Orders
) as O on (C.id = O.customerid)
where O.customerid is NULL;

2.用not in也能夠。 先用子查詢將買過東西的顧客id選出來。 而後排除這些顧客的id便可。code

select C.name as Customers
from Customers as C 
where C.id not in (
    select distinct customerid
    from Orders
) 

集合差定義:C=A-B。C中的元素等於在A中可是不在B中。所以,對A中的每一個元素a,若是元素a不在B中,則元素a就是集合C的元素。blog

EXISTS是布爾運算符,經常使用於測試子查詢。get

SELECT select_list FROM a_table WHERE [NOT] EXISTS(subquery);

當subquery返回任何行時,EXISTS返回true,不然返回false。table

select C.name as `Customers`
from Customers as C 
where not exists (
    select distinct customerid
    from Orders as O
    where O.customerid = C.id
) ;
相關文章
相關標籤/搜索