-
[MySQL] 'with 절' in Subquery데이터 공부하기 2022. 8. 29. 23:01
Subquery문을 활용할때 With 절을 사용하면
더 깔끔하게 작성을 할 수 있다.
1. 이런 코드가 있다고 가정하자
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_id2. 이렇게 계속 서브쿼리가 붙으면, inner join 안쪽이 너무 헷갈린다.
→ 그 때 쓰는 것이 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'데이터 공부하기' 카테고리의 다른 글
[MySQL] 실전 유용 문법 - Case (0) 2022.08.29 [MySQL] 실전 유용 문법 - 문자열 (0) 2022.08.29 [MySQL] 수업 4주차 - Subquery (0) 2022.08.29 [MySQL] 수업 3주차 - Join (0) 2022.08.08 [MySQL] SQL 중요 문법, 별칭 기능 Alias (0) 2022.08.01