[문제]
Table: Customers
id is the primary key column for this table.
Each row of this table indicates the ID and name of a customer.
Table: Orders
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:
참고) 문제링크
https://leetcode.com/problems/customers-who-never-order/
[문제 설명]
> 주문을 하지 않는 고객의 이름 구하기
- 구해야 하는 것
name - 필터 조건
LEFT JOIN을 하여 id가 null인 값 - 정렬
없음
[나의 풀이]
SELECT customers.name AS Customers
FROM customers
LEFT JOIN orders ON customers.id = orders.customerId
WHERE orders.id is null
출력결과
Customers |
Henry |
Max |
[설명]
1. LEFT JOIN
SELECT customers.name AS Customers
FROM customers
LEFT JOIN orders ON customers.id = orders.customerId
> customers 테이블(왼쪽 테이블)을 중심으로 orders 테이블(오른쪽 테이블)을 매치시킨다.
> orders 테이블(오른쪽 테이블)의 레코드가
customers 테이블(왼쪽 테이블)에 매치되는게 없으면
NULL값이 출력된다.
[LEFT JOIN의 특징]
> 왼쪽 테이블을 중심으로 오른쪽 테이블을 매치시킨다.
> 왼쪽 테이블에는 모든 레코드가 출력되고
오른쪽 테이블 레코드가 왼쪽 테이블에 매치되는게 없으면 NULL이 출력된다.
> 왼쪽 테이블의 한 개의 레코드에 여러 개의 오른쪽 테이블 레코드가 일치할 경우
왼쪽 레코드를 여러 번 출력된다.
2. WHERE절
SELECT customers.name AS Customers
FROM customers
LEFT JOIN orders ON customers.id = orders.customerId
WHERE orders.id is null
> LEFT JOIN한 레코드 중 id가 null인 값(주문을 안한 고객)을 출력한다.
'Test > MYSQL' 카테고리의 다른 글
Monthly Transactions I (DATE_FORMAT, CASE WHEN) (0) | 2023.05.28 |
---|---|
Reformat Department Table (CASE WHEN /THEN, GROUP BY) (0) | 2023.05.23 |
The Report (IF, INNER JOIN, BETWEEN /AND, ORDER BY) (0) | 2023.05.23 |
Symmetric Pairs (INNER JOIN, GROUP BY, HAVING, ORDER BY, UNION) (0) | 2023.05.19 |
Weather Observation Station 11 (SUBSTRING, NOT IN, LEFT, RIGHT) (0) | 2023.05.17 |