두 테이블을 공통된 필드를 기준으로 연결해서 한 테이블로 묶는 것.
a, b 테이블의 교집합, 즉 두 테이블에서 모두 가지고 있는 데이터만 출력됨
inner join users u
on o.user_id = u.user_id;
기준이 되는 테이블에 붙이고 싶은 테이블을 Join 절에 위치해 놓습니다.
inner join users u
on o.user_id = u.user_id
where u.email like '%naver.com'
group by u.name
where절 붙이고 group by 붙이기
select o.payment_method, round(AVG(p.point)) from point_users p
inner join orders o
on p.user_id = o.user_id
group by o.payment_method
select name, count(*) as cnt_name from enrolleds e
inner join users u
on e.user_id = u.user_id
where is_registered = 0
group by name
order by cnt_name desc
select c1.title, c2.week, count(*) as cnt from checkins c2
inner join courses c1 on c2.course_id = c1.course_id
group by c1.title, c2.week
order by c1.title, c2.week
select 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
order by c1.title, c2.week
b테이블을 a 테이블에 붙이는 것. 데이터가 비어있을 경우 '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
포인트를 가진 고객의 숫자, 그리고 전체 숫자, 그리고 비율을 보고 싶어요!
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'
결과물(select)들을 한번에 모아서 보고 싶을 때
대신 내부 order by가 적용되지 않음
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
)
SELECT e.enrolled_id ,e.user_id , COUNT(*) as cnt FROM enrolleds e
inner join enrolleds_detail ed on e.enrolled_id = ed.enrolled_id
where ed.done = 1
group by e.enrolled_id, e.user_id
order by cnt desc