문제
You are given three tables: Students, Friends and Packages. Students contains two columns: ID and Name. Friends contains two columns: ID and Friend_ID (ID of the ONLY best friend). Packages contains two columns: ID and Salary (offered salary in $ thousands per month).
Write a query to output the names of those students whose best friends got offered a higher salary than them. Names must be ordered by the salary amount offered to the best friends. It is guaranteed that no two students got same salary offer.
- 학생테이블 : ID 및 이름 / 친구테이블 : 아이디와 친구_ID(유일한 가장 친한 친구의 ID) / 패키지테이블 : ID 및 급여(월급은 수천 달러로 제공됨)
- 가장 친한 친구가 더 높은 연봉을 받는 학생들의 이름 출력
- 가장 친한 친구가 받는 salary를 오름차순 기준으로 정렬
- 중복값은 없다
코드
1. students의 이름을 출력해야하기 때문에 students 테이블을 기준으로 잡고 friends 조인하기
select a.id, b.friend_id -- 학생 아이디와 그 학생의 가장 친한 친구 아이디 조회
from students a
inner join friends b on (a.id = b.id)
2. 위 테이블에서 salary 데이터가 있는 packages 조인하여 내 salary와 친한 친구의 salary 구하기
select a.id, b.friend_id, c.salary, d.salary
from students a
inner join friends b on a.id = b.id
inner join packages c on a.id = c.id -- 내 salary 구하기
inner join packages d on b.friend_id = d.id -- 친한 친구의 salary 구하기
3. 내 salary보다 큰 친구 salary 조건으로 주기
select a.name
from students a
inner join friends b on a.id = b.id
inner join packages c on a.id = c.id
inner join packages d on b.friend_id = d.id
where c.salary < d.salary
order by d.salary
출처
반응형
'Algorithm > MySQL' 카테고리의 다른 글
[LeetCode] 175. Combine Two Tables (MySQL) (0) | 2021.07.13 |
---|---|
[해커랭크(HackerRank)] Top Competitors (MySQL) (0) | 2021.07.12 |
[해커랭크(HackerRank)] Weather Observation Station 3 (MySQL) (0) | 2021.07.12 |
[해커랭크(HackerRank)] Weather Observation Station 20 (MySQL) (0) | 2021.07.12 |
[해커랭크(HackerRank)] Weather Observation Station 19 (MySQL) (0) | 2021.07.10 |