SQL 기초 3일차 (2)

전윤환·2022년 3월 9일
0

SQL왕초보

목록 보기
4/6

SQL 기초 3일차 (2)
#스파르타코딩클럽, #내일배움단
학습일자: 2022/03/09
재수강일: 2022/04/29
삼수강일: 2022/05/01
강의: 엑셀보다 쉬운 SQL
진도: 3-1 ~ 3-4

자 드가자

=====================

JOIN

테이블들을 하나의 키값을 기준으로 하나의 테이블로 모아 보는 것

엑셀의 vlookup과 같은 기능이라고 합니다..

left join, inner join이 있다. (right join도 있으나 실무에서 쓸 확률 0%)

=====================

가운데 겹치는 부분은 공통된 키값을 의미.
left join은 합집합(?)
inner join은 교집합(?)

=====================


그림 1. left join을 사용한 테이블

그림 2. 일반 users 테이블

그림 3. 일반 point_users 테이블

select * from users u
left join point_users p
on u.user_id = p.user_id

from users < 얘가 왼쪽부터 컬럼을 채움
left join point_users < 얘가 그 뒤에 붙어서 채움

user_id < 얘가 맨 왼쪽에서 기준점을 줌

=====================

INNER JOIN

교집합이 null이 아닌 애들만 나옴
위에선 null이 종종 보이지만, inner join은 null이 없다.

select * from users u
inner join point_users p
on u.user_id = p.user_id

(left join에서 left만 inner로 바꿈)

(null이 없는 모습 확인)

즉, 교집합인 데이터만 가져온다고 생각하면 될듯

=====================

left join과 inner join의 차이점

left join : A에 B를 붙여라 (데이터 없으면 null로 보여주고)

inner join : A와 B 모두 만족하는 값을 불러와라

그러므로, left join은 뭐에 뭐를 붙일지 고민해야하지만
inner join은 일단 맞는거 보여주니까 초보자 입장에서 더 쉽다고 함

=====================
checkins 테이블에 users 테이블 붙이기

select * from checkins c
inner join users u
on c.user_id = u.user_id

=====================

쿼리가 실행되는 순서

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

from -> join -> select 순서
from에 들어간 테이블을 기준으로 join이 들어감

=====================

신~나는 문제풀이~~~ 아하!

checkins 테이블에 courses 테이블 연결해서 통계치 내보기
'오늘의 다짐' 정보에 과목 정보를 연결해 과목별 '오늘의 다짐' 갯수를 세어보자!

select c1.course_id, title, count(likes) as cnt from checkins c1
left join courses c2
on c1.course_id = c2.course_id
group by c1.course_id

count(likes) 대신 count(*)을 해도 같은 값이 나온다. 복습해봐야지...

=====================

select pu.user_id, u.email, u.name, pu.point from point_users pu
left join users u
on pu.user_id = u.user_id
order by pu.point DESC

=====================

select u.name, count(order_no) as cnt from orders o
left join users u
on o.user_id = u.user_id
where o.email like '%naver.com'
group by u.name
order by cnt desc


위 쿼리가 실행되는 순서: from → join → where → group by → order by → select

아 이거 좀 헷갈린다. where가 저기 들어가는군....

=====================

계~~속 퀴즈 풀기 조아요

결제 수단 별 유저 포인트의 평균값 구해보기
(어느 결제수단이 가장 열심히 듣고 있나~)

join 할 테이블: point_users 에, orders 를 붙이기

select o.payment_method as 결제수단, round(avg(point), 0) as 평균포인트 from point_users pu
inner join orders o
on pu.user_id = o.user_id
group by o.payment_method

=====================

결제하고 시작하지 않은 유저들을 성씨별로 세어보기
(어느 성이 가장 시작을 안하였는가~)

join 할 테이블: enrolleds 에, users 를 붙이기

select u.name, count(e.is_registered) as 미수강자 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 count(미수강자) desc

=====================

과목 별로 시작하지 않은 유저들을 세어보기

join 할 테이블: courses에, enrolleds 를 붙이기

select c.title as 과목, count(e.is_registered) as 미수강자 from courses c
inner join enrolleds e
on c.course_id = e.course_id
where e.is_registered = 0
group by c.title

=====================

웹개발, 앱개발 종합반의 week 별 체크인 수를 세어볼까요? 보기 좋게 정리해보기!

join 할 테이블: courses에, checkins 를 붙이기

select c.title, week, count(*)from courses c
inner join checkins c2
on c.course_id = c2.course_id
group by week, c.course_id
order by c.title, week

=====================

select c.title, week, count(*) from courses c
inner join checkins c2
on c.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 week, c.course_id
order by c.title, week

=====================

join 사용법에 대해 배웠다.
사실 전날 공부한 내용이 생각 안나서 잠깐 당황했다.
group by가 뭐였더라...어케 쓰더라...
count(*)를 써도 내가 원하는 결과값이 나오는 이유가 뭐였지..
암튼 sql은 재밌다. 후후... 재미를 느낄줄이야..고난의 연속일 줄 알았는데

간단하게 적어보는 join 사용법 1
select 필드 from 테이블1 (알리아스 지정)
inner join 테이블2 (알리아스 지정)
on 기준이 될 키값 = 다른 테이블의 키값
여기서, where를 쓰고싶다면 on 밑에!
group by, order by를 쓰고싶다면 where가 들어갈 자리보다 밑에!

profile
코딩 연습장. 발전하고 싶습니다. 모든 방향에서의 비판 부탁드립니다.

0개의 댓글