728x90
기본적으로 Customers join Orders 구조
select *
from customers c join orders o on c.ID = o.CustomerID
이 상태로 출력해보면
"headers": ["Id", "Name", "Id", "CustomerId"],
"values": [[1, "Joe", 2, 1],
[3, "Sam", 1, 3]]
이렇게 나온다.
따라서 left join이 필요하다.
select *
from customers c left join orders o on c.ID = o.CustomerID
left join의 결과는
{"headers": ["Id", "Name", "Id", "CustomerId"],
"values": [[1, "Joe", 2, 1],
[2, "Henry", null, null],
[3, "Sam", 1, 3],
[4, "Max", null, null]]}
이렇게 left인 customers에 있는 모든 row에 대해서 join 된 결과가 나오는데
원하는 결과는 null이 있는 row 중에서 Name을 rename한 결과물이다.
따라서
o.ID가 Null이거나
o.CustomerID가 Null인 rows만 출력하면 된다.
select c.Name as Customers
from customers c left join orders o on c.ID = o.CustomerID
where o.ID is null
# or
select c.Name as Customers
from customers c left join orders o on c.ID = o.CustomerID
where o.CustomerID is null
728x90
'SQL' 카테고리의 다른 글
[LeetCode] Rising Temperature (interval, self join) (0) | 2021.04.09 |
---|---|
[LeetCode] Delete Duplicate Emails (delete, self join, and) (0) | 2021.04.09 |
[LeetCode] Duplicate Emails (group by, having) (0) | 2021.04.09 |
[LeetCode] Employees Earning More Than Their Managers (Self Join) (0) | 2021.04.08 |
[LeetCode] Second Highest Salary MySQL (0) | 2021.04.08 |
댓글