Blair  - Soul Eater [leetcode] 175. Combine Two Tables

• data analysis/SQL

[leetcode] 175. Combine Two Tables

oujin 2024. 2. 16. 20:20
728x90

테이블 생성 코드

Create table If Not Exists Person (personId int, firstName varchar(255), lastName varchar(255))
Create table If Not Exists Address (addressId int, personId int, city varchar(255), state varchar(255))
Truncate table Person
insert into Person (personId, lastName, firstName) values ('1', 'Wang', 'Allen')
insert into Person (personId, lastName, firstName) values ('2', 'Alice', 'Bob')
Truncate table Address
insert into Address (addressId, personId, city, state) values ('1', '2', 'New York City', 'New York')
insert into Address (addressId, personId, city, state) values ('2', '3', 'Leetcode', 'California')
 
문제

 

Write a solution to report the first name, last name, city, and state of each person in the Person table. If the address of a personId is not present in the Address table, report null instead.

Return the result table in any order.

The result format is in the following example.

 

해결 코드

# Write your MySQL query statement below

SELECT firstName,lastName,city,state
FROM Person P
LEFT JOIN Address A ON P.personId = A.personId
 
 
해설
 
Person 테이블의 personId를 기준으로 LEFT JOIN을 한다. 그러면 Person 테이블에 있는 값은 모두 나오고 AddressPerson 과 기준이 일치하는 값의 행만을 가져온다
그러면 personId가 1,2인 값만으로 구성된 테이블이 만들어질 것이고 거기서 firstName,lastName,city,state 를 SELECT로 본다.
728x90

'• data analysis > SQL' 카테고리의 다른 글

1068. Product Sales Analysis I  (0) 2024.02.22
[leetcode] 1148. Article Views I  (0) 2024.02.20
[leetcode] 620. Not Boring Movies  (0) 2024.02.19
[leetcode] 595. Big Countries  (0) 2024.02.16
[leetcode] 182. Duplicate Emails  (0) 2024.02.16