-
[Leet Code] - 183. Customers Who Never OrderDataBase/LeetCode 2024. 10. 28. 21:59반응형
Table: Customers
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | +-------------+---------+ id is the primary key (column with unique values) 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 with unique values) for this table. customerId is a foreign key (reference columns) 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 a solution to find all customers who never order anything.
Return the result table in any order.
The 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 | +-----------+
두개의 테이블이 있다. Customers 그리고 Orders테이블
해당 고개들 중에서 한번도 주문을 하지 않은 사람을 찾기를 요구하고있다.
SELECT * FROM Customers AS C LEFT JOIN Orders AS O ON C.id = O.customerid
Customers테이블을 기준테이블로 설정하였고, customer테이블에 있는id컬럼과 orders에 있는 customerId컬럼을 기준으로 하여 Left조인을 하였다.
| id | name | id | customerId | | -- | ----- | ---- | ---------- | | 1 | Joe | 2 | 1 | | 2 | Henry | null | null | | 3 | Sam | 1 | 3 | | 4 | Max | null | null |
위의 쿼리를 실행하면 이와같은 결과가 나오게 된다. 여기서 NULL값이 있는 경우 가입만 한 상태에서 주문을 한 기록이 없는 유저들이다.
해당 문제에서 요구하는 상황은 주문기록이 없는 사용자들을 출력하라고 하니 아래와같이 수행하도록한다.
SELECT C.Name AS Customers FROM Customers AS C LEFT JOIN Orders AS O ON C.id = O.customerid WHERE O.id IS NULL
반응형'DataBase > LeetCode' 카테고리의 다른 글
LeetCode - 1179. Reformat Department Table (0) 2024.10.01