Join
- 두 테이블을 각각 조회하는 것이 아닌(두 번의 select), 두 테이블을 합친 것처럼 한 번의 조회로 두 곳의 데이터를 한 번에 찾는 방법
- 자신이 검색하고 싶은 컬럼이 다른 테이블에 있을 경우 주로 사용하며 여러 개의 테이블을 마치 하나의 테이블인 것처럼 활용하는 방법
- 데이터의 규모가 커지면서 하나의 테이블로 수용하기 어려워지면 테이블을 분할하고 테이블 간의 관계성을 부여
테이블의 연관 관계를 우선 파악
- 일대일, 일대다, 다대다 관계
- 외래 키 및 제약 조건 설정
Inner Join
- 서로 일치하는(존재하는) 데이터만 출력
- 두 테이블을 조인할 때, 두 테이블에 모두 지정한 열의 데이터가 있어야 한다.
Outer Join
- 한 쪽은 무조건 다 뿌리고, 나머지는 없으면 null로 출력
- 두 테이블을 조인할 때, 1개의 테이블에만 데이터가 있어도 결과가 나온다.
- Left, Right는 어느 테이블을 Driving으로 정하는 지에 따라 다름


테이블 생성과 더미 데이터
CREATE TABLE user_tb(
id int primary key auto_increment,
username varchar(20),
password varchar(20),
email varchar(100)
);
CREATE TABLE feed_tb(
id int primary key auto_increment,
title varchar(1000),
photo_url varchar(100),
user_id int
);
CREATE TABLE reply_tb(
id int primary key auto_increment,
content varchar(100),
user_id int,
feed_id int
);
-- 더미데이터
insert into user_tb(username, password, email) values('ssar', '1234', 'ssar@nate.com');
insert into user_tb(username, password, email) values('cos', '1234', 'cos@nate.com');
insert into user_tb(username, password, email) values('love', '1234', 'love@nate.com');
insert into feed_tb(title, photo_url, user_id) values('계곡왔어요', 'http://xn--989a5b.com', 1);
insert into feed_tb(title, photo_url, user_id) values('바다왔어요', 'http://xn--2j1b67o.com', 2);
insert into reply_tb(content, user_id, feed_id) values('굿', 2, 1);
insert into reply_tb(content, user_id, feed_id) values('별로', 3, 1);
user_tb

feed_tb

reply_tb

Inner Join
select *
from feed_tb ft inner join user_tb ut -- ft, ut: 별칭 / 테이블 퍼올림
on ft.user_id = ut.id; -- join 시작


select * from emp e inner join dept d
on e.deptno = d.deptno;


Inner Join 실패 사례
cos가 안 뜨므로 실패 사례 -> outer join 사용해야 함 !
select *
from feed_tb ft inner join user_tb ut on ft.user_id = ut.id
inner join reply_tb rt on ft.id = rt.feed_id;

Outer Join
내가 원하는 테이블에 모든 데이터를 다 뽑으면서 join하기 위해 사용
select *
from feed_tb ft inner join user_tb ut on ft.user_id = ut.id
left outer join reply_tb rt on ft.id = rt.feed_id;

화면 데이터 완성하기
select ft.title feed_title, ft.photo_url feed_picture, ut.username feed_writer, rt.content reply_content, rut.username reply_writer
from feed_tb ft inner join user_tb ut on ft.user_id = ut.id
left outer join reply_tb rt on ft.id = rt.feed_id
left outer join user_tb rut on rt.user_id = rut.id;
-- 정렬 추가
order by ft.id, rt.id;
-- Inline view Outer Join 예시
select post.feed_title, post.feed_picture, post.feed_writer, post.reply_content, rut.username reply_writer
from
(
select ft.title feed_title, ft.photo_url feed_picture, ut.username feed_writer, rt.content reply_content, rt.user_id reply_writer_id
from feed_tb ft inner join user_tb ut on ft.user_id = ut.id
left outer join reply_tb rt on ft.id = rt.feed_id
) post left outer join user_tb rut on post.reply_writer_id = rut.id;

Share article