Self join
Coddy SQL 여정의 기초 섹션에 포함된 레슨. 72개 중 46번째.
셀프 조인(Self-join)은 독특한 유형의 조인입니다. 지금까지는 여러 테이블 간의 조인을 다루었지만, 셀프 조인은 동일한 테이블 자신과 조인합니다. 대표적인 예로 employees 테이블을 들 수 있습니다.
| employee_id | employee_name | manager_id |
| 1 | Minke | 2 |
| 2 | Temur | 3 |
| 3 | Tatjana | 4 |
| 4 | Marinela |
최고 관리자를 제외한 모든 직원은 관리자가 있으며, 모든 관리자 역시 직원입니다.
문제: 각 직원별로 매니저의 이름을 알고 싶습니다.
SELECT e2.employee_id, e2.employee_name, e1.employee_name as manager_name
FROM employees as e1
JOIN employees as e2 ON e1.employee_id = e2.manager_id동일한 테이블을 조인하되 한 번은 e1이라 부르고 두 번째는 e2라고 부릅니다. 조인은 employee_id와 manager_id 필드 간에 이루어집니다.
결과:
| employee_id | employee_name | manager_name |
|---|---|---|
| 1 | Minke | Temur |
| 2 | Temur | Tatjana |
| 3 | Tatjana | Marinela |
챌린지
중급사용 가능한 테이블 및 컬럼:
<strong>friends</strong>:<strong>id</strong>,<strong>name</strong>,<strong>friend_id</strong>
맞친구인 친구 쌍을 찾으세요(맞친구 관계는 사람 A의 friend_id가 사람 B를 가리키고 동시에 사람 B의 friend_id가 사람 A를 가리킬 때 존재합니다). 두 친구의 이름을 단일 행에 표시하세요. 컬럼 이름을 friend1 및 friend2로 지정하세요.
참고: 중복 쌍이 포함되지 않도록 WHERE 절에 friend1.id < friend2.id 조건을 포함하세요.
직접 해보기
-- 테이블을 자기 자신과 조인하여 한 행에 서로 다른 두 사람을 보여줄 수 있게 함
SELECT ____ AS friend1, ____ AS friend2
FROM friends f1
JOIN friends f2 ON ____
-- 서로를 가리키는 쌍만 유지
WHERE ____ AND f1.id < f2.id;이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns직접 연습해 보세요: SQL 플레이그라운드