• 서브쿼리(subquery)란 다른 쿼리 내부에 포함되어 있는 SELETE 문을 의미하며 서브쿼리는 반드시 괄호(())로 감싸져 있어야한다.

 

1. Where 에 들어가는 Subquery

where 필드명 in (subquery)

select * from users u
where u.user_id in (select o.user_id from orders o 
					where o.payment_method = 'kakaopay');

 

 

2. Select 에 들어가는 Subquery

select 필드명, 필드명, (subquery) from...

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;

 

 

3. From 에 들어가는 Subquery 

주로 내가 만든 Select와 이미 있는 테이블을 Join하고 싶을 때 사용한다.

 

course_id별 유저의 체크인 개수 구하기

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

 

4. with절

with절은 동일한 SQL이 반복되어서 사용될 때 성능을 높이기 위해 사용된다.

table을 만들지 않고도 table 만든 것과 같은 효과를 내는데, 실제로는 temp라는 임시 테이블에 저장되는 것이다.

with
      cte1 as (select a, b from table 1),
      cte2 as (select c, d from table 2), ...

select a from cte1
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

'SQL' 카테고리의 다른 글

MySQL 접속  (0) 2023.06.14
실전에서 유용한 SQL 문법 (문자열, Case)  (0) 2023.05.04
SQL 2주차 - GROUP BY, ORDER BY  (0) 2023.05.04
SQL 3주차 - JOIN, UNION  (0) 2023.05.02
SQL 1주차 - BETWEEN, IN, LIKE, LIMIT  (0) 2023.04.27

+ Recent posts