[SQL] 기본개념 3

doyeonlee·2022년 2월 8일
0

개발일지 2022

목록 보기
13/16
post-thumbnail

기본개념

join

모든 실무에서 쓰이며,
left join : 왼쪽에 붙이기
inner join : 교집합

inner join

: 순서가 상관없다.

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

users 테이블(u)과 point_users 테이블(p)을 (공통으로 들어있는 field 인) user_id로 inner join 한다.

left join

: 순서에 상관이 있다.

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

users 테이블(u)과 point_users 테이블(p)을 (공통 field인) user_id로 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

is NULL은 데이터에 빈공간(구멍)이 있는,
is vot NULL은 데이터가 비지 않은

즉, 이는 어떠한 데이터가 존재하는 사람/ 존재하지 않는 사람을 구할때 적합하다.


쿼리 진행 순서

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

enrolleds 테이블(e)과 courses 테이블(c)을 course_id로 inner join 한다.
-항상 from에 들어간 테이블 기준으로 다른 테이블이 붙는다.

순서: from - join - select


개념활용 : inner join

ex1)

: 과목별 오늘의 다짐 갯수 세어보기

select co.title, count(co.title) as checkin_count from checkins ci
inner join courses co on ci.course_id = co.course_id 
group by co.title

checkins 테이블에 courses 테이블을 course_id를 기준으로 inner join 한다.
이를 courses 테이블의 title 필드로 group by 해주고,
보여지는 테이블은 title, group by로 묶어준 title의 수를 나타낸다.
여기서, group by로 묶어준 title은 checkin_count로 필드명을 바꿔준다.


ex2)

:많은 포인트를 얻은 순서대로 유저 데이터 정렬해서 보기

select * from point_users p 
inner join users u on p.user_id = u.user_id
order by p.point desc

ex3)

:네이버 이메일 사용하는 유저의 성씨별 주문건수 세어보기

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

순서: from - join - where - group by - select


profile
느려도 천천히 꼼꼼하게 !

0개의 댓글