Problem Solving

[LeetCode] Combine Two Tables

luminous13 2022. 11. 11. 17:47

문제

https://leetcode.com/problems/combine-two-tables/

 

Combine Two Tables - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

두 테이블을 결합(combine)해서 조회하는 문제.

풀이

Address 테이블에 personId 외래키가 있기 때문에 Join 연산을 사용하여 두 테이블을 합칠 수 있다.

결과를 보면 주소가 없는 회원들도 조회하기 때문에 left join을 해야된다.

1
2
3
4
select p.firstname, p.lastname, a.city, a.state
from person p
left join address a
on p.personid = a.personid;
cs

처음에 이런식으로 제출했고 통과가 되었다.

다른 사람들의 풀이를 보니깐 앞에 p, a와 같은 별명을 안붙였다. 

왜냐면 두 테이블에 중복되는 속성명이 아닐 경우에는 앞에 테이블 별명을 안붙여도 되기 때문이다.

따라서 다음과 같이 작성한게 더 깔끔하다.

1
2
3
4
select firstname, lastname, city, state
from person p
left join address a
on p.personid = a.personid;
cs