LeetCode:Customers Who Never Order - 從未下單的消費者

一、題目名稱sql

Customers Who Never Order(從未下單的消費者)數據庫

二、題目地址網站

https://leetcode.com/problems/customers-who-never-order/命令行

三、題目內容code

一個網站有兩張表,表Customers和表Orders,寫一個SQL找到全部未購買任何物品的顧客。leetcode

表Customers結構以下:get

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

表Orders結構以下:class

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

以上面兩張表爲例,查詢的結果集應爲:數據

+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

四、初始化數據庫腳本腳本

在MySQL數據庫中創建一個名爲LEETCODE的數據庫,用MySQL命令行中的source命令執行下面腳本:

-- 執行腳本前必須創建名爲LEETCODE的DATABASE
USE LEETCODE;
   
DROP TABLE IF EXISTS Customers;
CREATE TABLE Customers (
  Id INT NOT NULL PRIMARY KEY,
  Name VARCHAR(50)
);

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

DROP TABLE IF EXISTS Orders;
CREATE TABLE Orders (
  Id INT NOT NULL PRIMARY KEY,
  CustomerId INT
);

INSERT INTO Orders (Id, CustomerId) VALUES (1, 3);
INSERT INTO Orders (Id, CustomerId) VALUES (2, 1);

五、解題SQL1 - 使用 NOT IN

SELECT Name
FROM   Customers
WHERE  id NOT IN (SELECT CustomerId
                  FROM   Orders);

六、解題SQL2 - 使用 LEFT JOIN

SELECT Name AS Customers
FROM   Customers
LEFT   JOIN Orders ON Customers.Id = Orders.CustomerId
WHERE  Orders.CustomerId IS NULL;

七、解題SQL3 - 使用 NOT EXISTS

SELECT Name
FROM   Customers AS Cst
WHERE  NOT EXISTS (SELECT Ord.CustomerId
        FROM   Orders Ord
        WHERE  Cst.Id = Ord.CustomerId);

END

相關文章
相關標籤/搜索