[SQL]Join과 Union

야부엉·2023년 9월 26일

JOIN

  • JOIN이란?
    - 두 테이블의 공통된 정보(key값)를 기준으로 테이블을 연결해서 한 테이블처럼 사용할 때 쓴다.
  • inner join
	select name, count(*) from users
	group by name;
	- 실행 순서 : from -> group by -> select
  • left join
	- 기준이 되는 값(Key)에 의해 합쳐졌을 때, 다른 테이블에 값이 없는 경우 비어있는 값으로 적용된다.
    
  • inner join
	- 기준이 되는 값(key) 기준으로 교집합의 데이터 나온다.
    - 비어있는 필드 X -> 두 테이블에서 모두 가지고 있는 데이터만 출력된다.
  • 쿼리 실행 순서
    - from → join → select

예시에 사용되는 테이블별 특징

  • checkins: 여러분이 강의실 들어오시며 남기는 '오늘의 다짐'이 들어있어요
    - columns : checkin_id, created_at, updated_at, course_id, user_id, week, comment, likes

  • courses: 스파르타의 개설 강좌 정보가 들어있어요
    - columns : course_id, created_at, updated_at, title, description

  • enrolleds: 유저별 강좌 등록정보가 들어있어요
    - columns : enrolled_id, created_at, updated_at, course_id, user_id, is_registered

  • enrolleds_detail: 유저별 들을 수 있는 영상과, 들었는지 여부가 들어있어요
    - columns : enrolled_detail_id, enrolled_id, week, current_order ,done, seen, done_date, seen_date

  • orders: 주문 (수강등록) 정보가 들어있어요
    - columns : order_no, created_at, updated_at, course_id, course_title, user_id, payment_method, email

  • point_users: 유저별 포인트 점수가 들어있어요
    - columns : point_user_id, created_at, updated_at, user_id, point

  • users: 유저 정보가 들어있어요
    - columns : user_id, created_at, updated_at, name, email


사용 예시

  1. inner join 기본적인 사용법
	select * from checkins c
	inner join users u
	on c.user_id = u.user_id;
  1. left join 기본적인 사용법
	select * from users u
	left join point_users pu on u.user_id = pu.user_id
  1. 결제하고 시작하지 않은 유저들을 성씨별로 세어보기
	select u.name, COUNT(*) as cnt from enrolleds e 
	inner join users u 
	on e.user_id = u.user_id 
	where e.is_registered = 0
	group by u.name 
	order by cnt desc
  1. 웹개발, 앱개발 종합반의 week 별 체크인 수에서 8월 1일 이후에 구매한 고객들의 데이터 확인
	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 
  1. 7월10일 ~ 7월19일에 가입한 고객 중, 포인트를 가진 고객의 숫자, 그리고 전체 숫자, 그리고 비율 데이터 확인
	select count(pu.point_user_id) as pnt_user_cnt, 
       count(u.user_id) as tot_user_cnt, 
       round(count(pu.point_user_id)/count(u.user_id), 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'

UNION

  • 사용 이유 : 결과물을 합쳐서 한번에 모아서 보고싶은 경우 사용

사용 예시

  1. 7월과 8월에 대한 데이터를 한번에 확인
    (
	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
	)

profile
밤낮없는개발자

0개의 댓글