728x90
with절
subquery가 너무 많아서 알아보기 힘들 때 사용
서브쿼리가 많아져서 지저분해 보임
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절로 정리해줌
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
한눈에 보기에 편해진다.
서브쿼리들에 미리 별칭을 붙여놨다가 메인 쿼리에서 꺼내 쓴다.
728x90
'개발일지 > DataBase' 카테고리의 다른 글
Mysql 포트 변경 - MacOs M2 (0) | 2023.05.06 |
---|---|
Substring_Index, Substring, Case (0) | 2022.07.02 |
Subquery (0) | 2022.07.02 |
Union (0) | 2022.07.02 |
Join (0) | 2022.07.02 |