본문 바로가기
SQL

[LeetCode] Customes Who Never Order (is null, join)

by YGSEO 2021. 4. 9.
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

댓글