SQL_3주차 개발일지 (Join)

이민희·2022년 8월 26일
0

SQL 일지

목록 보기
5/5

Join

서로 다른 테이블을 연결해줄 수 있는 기능 (excel : vlookup)

Join 종류

  • left join : 왼쪽에 있는 테이블 기준으로 추가, NULL값 존재
select * from users u
left join point_users p
on u.user_id = p.user_id;
  • inner join_on : 교집합된 내용만 출력
select * from users u
inner join point_users p
on u.user_id = p.user_id;

🗨️Left Join, Inner join
두 개가 다른 join이기 때문에 당연히 count(*)을 하게되면 서로 다른 전체 값을 가지게 됨!

모든 내용을 다 담고 있는 테이블이 더 좋을 것 아닐까?
➡️ Nope! 한 가지의 목적에 맞는 것들을 나눠놓는 것들이 가장 좋음!
👀 Why? 간편하고, 수정이 간편하다는 장점이 있다.
🚨 Then How to join?
-서로 다른 테이블의 공통된 정보 (key값)를 기준으로 테이블을 연결해서 한 테이블처럼 볼 수 있음!

[실습] enrolleds 테이블에 courses 테이블 연결해보기

SELECT * from enrolleds e 
inner join courses c 
on e.course_id = c.course_id 

결제 수단 별 유저 포인트의 평균값 구해보기

SELECT o.payment_method , round(avg(point)) from point_users pu 
inner join orders o on pu.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 title, count(*) from courses c 
inner join enrolleds e on c.course_id = e.course_id 
where e.is_registered = 0
group by c.title 

웹개발, 앱개발 종합반의 week 별 체크인 수를 세어볼까요?

SELECT title, week, count(*) as cnt from courses c 
inner join checkins ch on c.course_id = ch.course_id 
group by c.title , week
order by c.title , week

8월 1일 이후에 구매한 고객들만 발라내어 보세요!

SELECT c.title , ch.week, count(*) from courses c 
inner join checkins ch on c.course_id = ch.course_id 
inner join orders o on ch.user_id = o.user_id 
where o.created_at >= '2020.08.01'
group by c.title , ch.week 
order by c.title , ch.week 

🚨날짜 설정시 유의사항!

  • 내가 만약 "7월 10일~19일" 사이에 일어난 데이터를 원한다면?
    ➡️Where A between '2020-07-10' and '2020-07-20'
    👀Why? 기본 커리값이 '2020-07-20' 00:00:00을 가지기 때문!

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'

Union All

Select를 두 번 할 게 아니라, 한번에 모아서 보고싶은 경우

  • order by : 따로 적용되지 않기 때문에 삭제해도 무방!
    그런데 정렬을 하고싶다? ➡️4주차 서브쿼리 개념이 필요!
profile
뮤지컬 무대감독 출신, PM/PO를 꿈꾸는 메모리입니다.

0개의 댓글