day24 TIL
day24 느낀점
오늘도 데이터베이스 강의를 위주로 들었다. 다양하게 연습을 해볼 수 있어서 좋다. 내일은 완강해야지! 그리고 스프링강의를 듣고있다. annotation 강의랑 공식문서를 보면서 좀 정리를 해야겠다. 오늘 til은 sql 조인이랑 서브쿼리 관하여 정리해보았다.
두 테이블의 공통된 정보를 key값을 기분으로 테이블을 연결하여 한 테이블처럼 보는 것을 의미한다.
select *
from table1 t1
inner join table2 t2
on t1.idx = t2.idx;
select *
from table1 t1
left join table2 t2
on t1.idx = t2.idx
where t2.idx2 is NULL;
table2에 idx2값이 없는 사람들의 통계를 낼 수 있음
쿼리 안의 쿼리를 의미하며 더 간단하게 sql 쿼리를 작성할 수 있다.
select u.user_id, u.name, u.email from users u
where u.user_id in (
select user_id from orders
where payment_method = 'kakaopay'
)
서브쿼리에 있는 user_id 값에 포함되는 데이터만 필터링하여 출력할 수 있다.
select c.checkin_id, c.user_id, c.likes,
(select avg(likes) from checkins c2
where c2.user_id = c.user_id) as avg_like_user
from checkins c;
각 데이터마다 사용자의 평균 좋아요값을 출력한다.
이는 데이터를 한줄한줄 출력할때 매번 실행
단, 이때 서브쿼리가 리턴하는 값은 하나여야한다.
select pu.user_id, a.avg_like, pu.point from point_users pu
inner join (
select user_id, round(avg(likes),1) as avg_like from checkins
group by user_id
) a on pu.user_id = a.user_id
이미 있는 테이블들을 조인을 사용하여 새롭게 만들어 셀렉트문을 작성할때 사용한다.
이는 가장 자주 사용되는 서브쿼리 유형이다.
+++ with절로 쿼리문 정리하기
select c.title,
a.cnt_checkins,
b.cnt_total,
(a.cnt_checkins/b.cnt_total) as ratio
from
(
select course_id, count(distinct(user_id)) as cnt_checkins from checkins
group by course_id
) a
inner join
(
select course_id, count(*) as cnt_total from orders
group by course_id
) b on a.course_id = b.course_id
inner join courses c on a.course_id = c.course_id
with table1 as (
select course_id, count(distinct(user_id)) as cnt_checkins from checkins
group by course_id
), table2 as (
select course_id, count(*) as cnt_total from orders
group by course_id
)
select c.title,
a.cnt_checkins,
b.cnt_total,
(a.cnt_checkins/b.cnt_total) as ratio
from table1 a inner join table2 b on a.course_id = b.course_id
inner join courses c on a.course_id = c.course_id
with를 통해 미리 테이블을 정의해놓아 서브쿼리를 간단하게 정리할 수 있다.