서브쿼리는 다른 SQL문 안에 중첩된 SELECT 문
국가가 ‘Brasil’인 유저의 주문정보(orders)를 조회 하는 쿼리입니다
select *
from `thelook_ecommerce.orders` o
where user_id in (
select id
from `thelook_ecommerce.users`
where country = 'Brasil'
);
주문수가 3건 이상인 유저의 id와 이름을 조회합니다.
select user_id,
from `thelook_ecommerce.orders`
group by user_id
having count(order_id)>=3
select id, first_name, last_name
from `thelook_ecommerce.users`
where id in(
select user_id
from `thelook_ecommerce.orders`
group by user_id
having count(order_id)>=3
)
유저의 id와 이름 그리고 주문수를 조회
users테이블의 정보와 user별 주문수를 조회하는 서브쿼리를 left join을 이용하여 연결해서 유저의 주문수를 조회
select u.id, o.order_count
from `thelook_ecommerce.users` u
join (
select user_id, count(order_id) as order_count
from `thelook_ecommerce.orders`
group by user_id
)o on u.id = o.user_id
user 정보를 조회합니다. 해당 유저의 주문수(order_count)를 조회하기 위해 select 절에서 서브쿼리를 사용하였습니다.
select id,
first_name,
last_name,
(select count(order_id) from `thelook_ecommerce.orders` where user_id = u.id )as order_count
from `thelook_ecommerce.users` u
order by order_count desc
with 절은 쿼리 내에서 임시 결과를 정의하고 사용합니다.