SQL join - swkim0128/PARA GitHub Wiki
๋ ์ด์์ ํ ์ด๋ธ์์ ๋ฐ์ดํฐ๊ฐ ํ์ํ ๊ฒฝ์ฐ ํ ์ด๋ธ ์กฐ์ธ์ด ํ์.
์ผ๋ฐ์ ์ผ๋ก ์กฐ์ธ ์กฐ๊ฑด์ ํฌํจํ๋ where ์ ์ ์์ฑํด์ผ ํ๋ค.
์กฐ์ธ ์กฐ๊ฑด์ ์ผ๋ฐ์ ์ผ๋ก ๊ฐํ ์ด๋ธ์ PK ๋ฐ FK๋ก ๊ตฌ์ฑ๋ฉ๋๋ค.
join์ ์ข ๋ฅ
- inner join
- outer join
- left outer join
- right outer join
join ์กฐ๊ฑด์ ๋ช ์์ ๋ฐ๋ฅธ ๊ตฌ๋ถ.
- natural join
- cross join(full join, cartesian join)
join์ ์ฃผ์
- ์กฐ์ธ์ ์ฒ๋ฆฌ๋ ์ด๋ ํ ์ด๋ธ์ ๋จผ์ ์ฝ์์ง๋ฅผ ๊ฒฐ์ ํ๋ ๊ฒ์ด ์ค์(์ฒ๋ฆฌํ ์์ ๋์ด ์๋นํ ๋ฌ๋ผ์ง๋ค.)
- inner join : ์ด๋ ํ ์ด๋ธ์ ๋จผ์ ์ฝ์ด๋ ๊ฒฐ๊ณผ๊ฐ ๋ฌ๋ผ์ง์ง ์์ mysql ์ตํฐ๋ง์ด์ ๊ฐ ์กฐ์ธ์ ์์๋ฅผ ์กฐ์ ํด์ ๋ค์ํ ๋ฐฉ๋ฒ์ผ๋ก ์ต์ ํ๋ฅผ ์ํํ ์ ์๋ค.
- outer join : ๋ฐ๋์ outer๊ฐ ๋๋ ํ ์ด๋ธ์ ๋จผ์ ์ฝ์ด์ผ ํ๋ฏ๋ก ์ตํฐ๋ง์ด์ ๊ฐ ์กฐ์ธ ์์๋ฅผ ์ ํํ ์ ์๋ค.
๊ฐ์ฅ ์ผ๋ฐ์ ์ธ join์ ์ข ๋ฅ์ด๋ฉฐ ๊ต์งํฉ์ด๋ค.
๋๋ฑ ์กฐ์ธ(uqui-join)์ด๋ผ๊ณ ๋ ํ๋ฉฐ, N๊ฐ์ ํ ์ด๋ธ ์กฐ์ธ ์ N - 1๊ฐ์ ์กฐ์ธ ์กฐ๊ฑด์ด ํ์ํจ.
> select col1, col2, ..., colN
from table1 inner join table2
on table1.column = table2.column;
> select alias1.col1, alias1.col2, ..., alias2.colN
from table1 as asias1 inner join table2 as alias2
on alias1.column = alias2.column;
-
on์ ์ด์ฉํ join ์กฐ๊ฑด ์ง์ .
-
using์ ์ด์ฉํ join ์กฐ๊ฑด ์ง์ .
> select col1, col2, ..., colN from table1 join table2 using (๊ณตํต column);
> select col1, col2, ..., colN
from table1 natural join table2;
left outer join, right outer join, full outer join์ผ๋ก ๊ตฌ๋ถ ๋จ.
์ด๋ ํ์ชฝ ํ ์ด๋ธ์๋ ํด๋นํ๋ ๋ฐ์ดํฐ๊ฐ ์กด์ฌํ๋๋ฐ ๋ค๋ฅธ ์ชฝ ํ ์ด๋ธ์๋ ๋ฐ์ดํฐ๊ฐ ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ ๊ทธ ๋ฐ์ดํฐ๊ฐ ๊ฒ์๋์ง ์๋ ๋ฌธ์ ์ ์ ํด๊ฒฐํ๊ธฐ ์ํด ์ฌ์ฉ.
left outer join
-
์ผ์ชฝ ํ ์ด๋ธ์ ๊ธฐ์ค์ผ๋ก join ์กฐ๊ฑด์ ์ผ์น ํ์ง ์๋ ๋ฐ์ดํฐ๊น์ง ์ถ๋ ฅ
> select col1, col2, ..., colN from table1 left outer join table2 on or using;
right outrer join
- ์ค๋ฅธ์ชฝ ํ ์ด๋ธ์ ๊ธฐ์ค์ผ๋ก join์กฐ๊ฑด์ ์ผ์นํ์ง ์๋ ๋ฐ์ดํฐ๊น์ง ์ถ๋ ฅ.
> select col1, col2, ..., colN
from table1 right outer join table2
on or using;
full outer join
- ์์ชฝ ํ ์ด๋ธ์ ๊ธฐ์ค์ผ๋ก join ์กฐ๊ฑด์ ์ผ์นํ์ง ์๋ ๋ฐ์ดํฐ๊น์ง ์ถ๋ ฅ.
> select col1, col2, ... colN
from table1 full outer join table2
on or using
self join
- ๊ฐ์ ํ ์ด๋ธ๋ผ๋ฆฌ join
- ๋ชจ๋ ์ฌ์์ ์ฌ๋ฒ, ์ด๋ฆ, ๋งค๋์ ์ฌ๋ฒ, ๋งค๋์ ์ด๋ฆ
select e.employee_id, e.first_name, m.employee_id, m.first_name
from employees e inner join employees m
on e.manager_id = m.employee_id;
None-Equi join
- table์ pk, fk๊ฐ ์๋ ์ผ๋ฐ column์ join ์กฐ๊ฑด์ผ๋ก ์ง์ .
- ๋ชจ๋ ์ฌ์์ ์ฌ๋ฒ, ์ด๋ฆ, ๊ธ์ฌ, ๊ธ์ฌ ๋ฑ๊ธ.