SQL 기초3 _ join, union

백지연·2022년 11월 27일
0

5. join

join 이란?

두 테이블의 공통된 정보 (key값)를 기준으로 테이블을 연결해서 한 테이블처럼 보는 것

예) user_id 필드를 기준으로 users 테이블과 orders 테이블을 연결해서 한 눈에 보고 싶어요!

1) left join
어떤 데이터는 모든 필드가 채워져있지만, 어떤 데이터는 비어있는 필드존재

유저 중에, 포인트가 없는 사람(=즉, 시작하지 않은 사람들)의 통계!
속닥속닥) is NULL , is not NULL 을 함께 배워보아요!

select name, count(*) 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
select name, count(*) 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(point_user_id) as pnt_user_cnt,
count() as tot_user_cnt,
round(count(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
비어있는 필드가 있는 데이터가 없음(교집합)

select u.name, count(u.name) as count_name from orders o
inner join users u
on o.user_id = u.user_id
where u.email like '%naver.com'
group by u.name


## 6. Union 
#### union 활용법
Select를 두 번 할 게 아니라, 한번에 모아서 보고싶은 경우(결과물 합치기)

(
select '7월' as month, c.title, c2.week, count() as cnt from checkins c2
inner join courses c on c2.course_id = c.course_id
inner join orders o on o.user_id = c2.user_id
where o.created_at < '2020-08-01'
group by c2.course_id, c2.week
order by c2.course_id, c2.week
)
union all
(
select '8월' as month, c.title, c2.week, count(
) as cnt from checkins c2
inner join courses c on c2.course_id = c.course_id
inner join orders o on o.user_id = c2.user_id
where o.created_at > '2020-08-01'
group by c2.course_id, c2.week
order by c2.course_id, c2.week
)


단, union을 사용하면 내부 정렬이 먹지 않음. 
→ 이 때 SubQuery(서브쿼리) 사용
profile
문어발 공부

0개의 댓글