▌刷題回顧web
【SQL刷題系列】:leetcode178 Rank Scores
app
▌題目描述ide
Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.網站
假設一個網站包含兩個表: Customers和Orders。寫出一個SQL查詢語句找出全部沒有任何訂單的顧客。spa
Customers表:3d
+----+-------+ | Id | Name | +----+-------+ | 1 | Joe | | 2 | Henry | | 3 | Sam | | 4 | Max | +----+-------+
Orders表:code
+----+------------+ | Id | CustomerId | +----+------------+ | 1 | 3 | | 2 | 1 | +----+------------+
使用上面兩個表,你的查詢結果應該與下面這樣相同。orm
+-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+
▌參考答案ci
參考1:leetcode
select Name as Customers from Customers
where Id not in (select distinct CustomerId from Orders);
參考2:
select name AS Customers
from Customers LEFT JOIN Orders
ON Customers.Id=Orders.CustomerId
WHERE Orders.CustomerId IS NULL;
▌答案解析
參考1:經過查詢select的嵌套使用。先在Orders表中返回全部有訂單的客戶Id,而後在Customer查詢不在Orders表中的客戶Id,最後返回相應的用戶名字,即爲最終結果。固然,也能夠使用join經過鏈接兩個表來實現
參考2:將Customers表的Id與Orders表的CustomerId創建左鏈接,那麼Orders本來缺乏的信息就會自動用NULL來代替。而後用where查詢是NULL的用戶名字便可。