๐ชข Join
- ์ฌ๋ฌ ์ ๋ณด๋ฅผ ํ ๋์ ๋ณด๊ณ ์ถ์ ๋ ์ฌ์ฉํ๋ค.
- ๋ ํ ์ด๋ธ์ ๊ณตํต๋ ์ ๋ณด(key๊ฐ) ๊ธฐ์ค์ผ๋ก ํ ์ด๋ธ์ ์ฐ๊ฒฐํด์ ํ ํ ์ด๋ธ์ฒ๋ผ ๋ณด๋ ๊ฒ
- point_user ํ ์ด๋ธ๊ณผ users ํ ์ด๋ธ์ ์ฐ๊ฒฐํด์ค. -> ๊ณตํต๋ ํค๊ฐ์ 'user_id'
select * from point_users
left join users
on point_users.user_id = users.user_id
1) Left Join
- ์ผ์ชฝ ํ ์ด๋ธ์ ์ค์ฌ์ผ๋ก ์ค๋ฅธ์ชฝ์ ํ ์ด๋ธ์ ์ฐ๊ฒฐํ๋ค.
- ์ด๋ค ๋ฐ์ดํฐ๋ ๋ชจ๋ ํ๋๊ฐ ์ฑ์์ ธ์์ง๋ง, ์ด๋ค ๋ฐ์ดํฐ๋ ๋น์ด์๋ ํ๋๊ฐ ์๋ค.
- ex) ํ์์ด์ง๋ง ์๊ฐ ๋ฑ๋ก ๋๋ ์์ํ์ง ์์ ํฌ์ธํธ๊ฐ null ๊ฐ์ผ๋
https://www.w3schools.com/sql/sql_join_left.asp
- users ํ ์ด๋ธ๊ณผ point_users ํ ์ด๋ธ left join ํด๋ณด๊ธฐ
๐โ๏ธ ์คํ๋๋ ์์
from -> join -> select
1) from users: users ํ ์ด๋ธ ๋ฐ์ดํฐ ์ ์ฒด๋ฅผ ๊ฐ์ ธ์จ๋ค.
2) inner join point_users p on u.user_id = p.user_id: users ํ ์ด๋ธ ๊ธฐ์ค์ผ๋ก point_users ํ ์ด๋ธ์ ์ฐ๊ฒฐํ๋ค.
3) select *
select * from users u
left join point_users pu on u.user_id = pu.user_id
๐โ๏ธ u, pu??
- users ํ ์ด๋ธ๊ณผ point_users ํ ์ด๋ธ์ ๋ณ์นญ
- ํฌ์ธํธ๊ฐ ์๋ ์ ์ ๋ค์ ๋ฐ์ดํฐ๋ค๋ง ๋ณด์ฌ์ค. is NULL
select * from users u
left join point_users pu on u.user_id = pu.user_id
where pu.point_user_id is NULL
group by name
- ํฌ์ธํธ๊ฐ ์ง๊ธ๋ ์ ์ ๋ค์ ๋ฐ์ดํฐ๋ค๋ง ๋ณด์ฌ์ค. is not NULL
select * from users u
left join point_users pu on u.user_id = pu.user_id
where pu.point_user_id is not NULL
group by name
- 7์ 10์ผ ~ 7์ 19์ผ ๊ฐ์ ํ ๊ณ ๊ฐ ์ค, ํฌ์ธํธ๋ฅผ ๊ฐ์ง ๊ณ ๊ฐ์ ์ซ์, ๋น์จ ๊ฐ์ ธ์์ค.
select count(pu.point_user_id) as pnt_user_cnt,
round(count(pu.point_user_id)/count(*), 2) as ratio
from users u
left join point_users pu on u.user_id = pu.user_id
where u.created_at between '2020-07-10' and '2020-07-20'
2) Inner join
- ๋ ํ ์ด๋ธ์ ๊ต์งํฉ
https://www.w3schools.com/sql/sql_join_inner.asp
- users ํ ์ด๋ธ๊ณผ point_users ํ ์ด๋ธ inner join ํด๋ณด๊ธฐ
๐โ๏ธ ์คํ๋๋ ์์
from -> join -> select
1) from users: users ํ ์ด๋ธ ๋ฐ์ดํฐ ์ ์ฒด๋ฅผ ๊ฐ์ ธ์จ๋ค.
2) inner join point_users p on u.user_id = p.user_id: users ํ ์ด๋ธ์ ์๋ user_id ํค๊ฐ๊ณผ
point_users ํ ์ด๋ธ์ ์๋ user_id ํค๊ฐ๋ผ๋ฆฌ ์ฐ๊ฒฐํด์ค๋ค. ์ด ๋ ๊ต์งํฉ์ ํน์ฑ๋๋ก ๊ณตํต์ ์ธ ๋ถ๋ถ๋ง ์ฐ๊ฒฐํ๋ค.
3) select *
select * from users u
inner join point_users p on u.user_id = p.user_id;
๐ฉน Union
- select 2๋ฒ์ ํจ๊ณผ
(
select '7์' as month, c1.title, c2.week, count(*) as cnt from courses c1
inner join checkins c2 on c1.course_id = c2.course_id
inner join orders o on c2.user_id = o.user_id
where o.created_at >= '2020-08-01'
group by c1.title, c2.week
)
union all
(
select '8์' as month, c1.title, c2.week, count(*) as cnt from courses c1
inner join checkins c2 on c1.course_id = c2.course_id
inner join orders o on c2.user_id = o.user_id
where o.created_at >= '2020-08-01'
group by c1.title, c2.week
)