183.Customers Who Never Order

https://leetcode.com/problems/customers-who-never-order/submissions/950803509/

문제설명

Table: Customers

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
+-------------+---------+
id is the primary key column for this table.
Each row of this table indicates the ID and name of a customer.

Table: Orders

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| customerId  | int  |
+-------------+------+
id is the primary key column for this table.
customerId is a foreign key of the ID from the Customers table.
Each row of this table indicates the ID of an order and the ID of the customer who ordered it.

Write an SQL query to report all customers who never order anything.

Return the result table in any order.

The query result format is in the following example.

Example 1:

Input:
Customers table:
+----+-------+
| id | name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+
Orders table:
+----+------------+
| id | customerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+
Output:
+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

Orders 테이블의 customerId를 포함하지 않는 Customers 테이블의 id의 name 조회하기


풀이

SELECT name AS Customers
FROM Customers
WHERE id not in (SELECT customerId FROM Orders);

다른풀이

SELECT tt.name AS Customers FROM
(
    SELECT cust.name, ord.id 
    FROM Customers cust 
    LEFT JOIN Orders ord
    ON cust.id = ord.customerId
) AS tt
WHERE tt.id IS NULL