CS/Database

[RDBMS] SQL JOIN(2) - LEFT OUTER JOIN

칸타탓 2019. 5. 27. 01:41

LEFT OUTER JOIN

 

https://sql-joins.leopard.in.ua/

 

* 실습 테이블

topic
tid title description author_id
1 HTML HTML is … 1
2 CSS CSS is … 2
3 Database Database is .. 1
4 Oracle Oracle is … NULL
author
aid name city profile_id
1 egoing seoul 1
2 leezche jeju 2
3 blackdew namhae 3
profile
pid title description
1 developer developer is …
2 designer designer is …
3 DBA DBA is ..

 

* left (outer) join

topic의 4행을 보면 NULL 값이 존재한다. author의 정보가 필요 없는 경우

또, author의 3행은 topic에 존재하지 않는다.

 

SELECT * FROM topic LEFT JOIN author ON topic.author_id = author.aid;

tid title description author_id aid name city profile_id
1 HTML HTML is … 1 1 egoing seoul 1
2 CSS CSS is … 2 2 leezche jeju 2
3 Database Database is .. 1 1 egoing seoul 1
4 Oracle Oracle is … NULL NULL NULL NULL NULL

일단 왼쪽에 있는 topic 테이블을 기준으로 가져온 후에, author_id = aid가 같은 author테이블을 오른쪽에 그대로 가져온다.

그리고 없는 부분은 모두 NULL로 채움.

=> 가장 많이 사용

 

* 2개 이상의 테이블 left outer join

뒤에 또 LEFT JOIN을 붙여주면 된다. profile_id = pid를 비교하여 추가한다.

 

SELECT * FROM topic LEFT JOIN author ON topic.author_id = author.aid LEFT JOIN profile ON author.profile_id = profile.pid;

tid title desc author_id aid name city profile_id pid title description
1 HTML HTML is … 1 1 egoing seoul 1 1 developer developer is …
2 CSS CSS is … 2 2 leezche jeju 2 2 designer designer is …
3 Database Database is .. 1 1 egoing seoul 1 1 developer developer is …
4 Oracle Oracle is … 3 NULL NULL NULL NULL NULL NULL NULL

 

* tid, aid, pid와 같이 중복되는 부분이 존재하는데 이를 제거하기 위해서는 출력 될 컬럼을 지정하면 된다.

모호성을 제거하기 위해 테이블명.컬럼명으로 사용함.

별칭을 부여하기 위해서는 AS를 추가하면 됨.

 

SELECT tid, topic.title, author_id, name, profile.title AS job_title FROM topic LEFT JOIN author ON topic.author_id = author.aid LEFT JOIN profile ON author.profile_id = profile.pid;

tid title name aid job_title (별칭)
1 HTML egoing 1 developer
2 CSS leezche 2 designer
3 Database egoing 1 developer
4 Oracle NULL 3 NULLL

 

* 특정 값만 가져오기

WHERE절을 사용한다.

 

SELECT tid, topic.title, author_id, name, profile.title AS job_title FROM topic LEFT JOIN author ON topic.author_id = author.aid LEFT JOIN profile ON author.profile_id = profile.pid WHERE aid = 1;

tid title name aid job_title
1 HTML egoing 1 developer
3 Database egoing 1 developer

 

* RIGHT OUTER JOIN

기준 행이 왼쪽에서 오른쪽으로 바뀐다. 방향만 달라졌을 뿐 LEFT JOIN과 비슷하게 동작한다.

'CS > Database' 카테고리의 다른 글

[RDBMS] SQL JOIN(4) - FULL OUTER JOIN, EXCLUSIVE LEFT JOIN  (0) 2019.05.27
[RDBMS] SQL JOIN(3) - INNER JOIN  (0) 2019.05.27
[RDBMS] SQL JOIN(1) - JOIN  (0) 2019.05.27