Subquery
νλμ SQL 쿼리 μμ λ λ€λ₯Έ SQL μΏΌλ¦¬κ° μλ κ²μ μλ―Ένλ€ !
where
μμwhere
쑰건문μμ Subqueryμ κ²°κ³Όλ₯Ό 쑰건μ νμ©νλ λ°©μμΌλ‘ μ μ©νκ² μ¬μ©νλ€.
where (νλλͺ
) in (Subquery)
μΏΌλ¦¬κ° μ§νλλ μμ
β‘οΈfrom
μ€ν β‘οΈSubquery
μ€ν β‘οΈwhere
β‘οΈ μ‘°κ±΄μ λ§λ κ²°κ³Ό μΆλ ₯
select * from users u
where u.user_id in (select o.user_id from orders o
where o.payment_method = 'kakaopay');
1) from
μ€ν: users
λ°μ΄ν°λ₯Ό κ°μ Έμμ€λ€.
2) Subquery
μ€ν: ν΄λΉλλ user_id
μ λͺ
λ¨μ λ½μμ€λ€.
3) where ... in
μ μμ Subquery
κ²°κ³Όμ ν΄λΉλλ "user_id
μ λͺ
λ¨" 쑰건μΌλ‘ νν°λ§μ ν΄μ€λ€.
4) 쑰건μ λ§λ κ²°κ³Ό μΆλ ₯
select
μμselect
λ κ²°κ³Όλ μΆλ ₯ν΄μ£Όλ λΆλΆμ΄λ€. κΈ°μ‘΄ ν
μ΄λΈμμ ν¨κ» λ³΄κ³ μΆμ ν΅κ³ λ°μ΄ν°λ₯Ό μ½κ² λΆμΌ λ μ¬μ©νλ€.
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;
1) λ°μ select * from
λ¬Έμμ λ°μ΄ν°λ₯Ό νμ€νμ€ μΆλ ₯νλ κ³Όμ μμ
2) select
μμ Subquery
κ° λ§€ λ°μ΄ν°λ₯Ό νμ€λ§λ€ μ€νλλ€.
3) κ·Έ λ°μ΄ν° ν μ€μ user_id
λ₯Ό κ°λ λ°μ΄ν°μ κ°μ Subquery
μμ κ³μ°νλ€.
4) ν¨κ» μΆλ ₯λλ€.
from
μμβοΈ λ§μ΄ μ¬μ© βοΈ
select
μ μ΄λ―Έ μλ ν
μ΄λΈμ join
ν λ μ¬μ©νλ€.
select νλλͺ
from (Subquery)
select course_id from
(
select course_id, count(*) as cnt_total from orders
group by course_id
)
λ¨Όμ Subquery
κ° μ€νλκ³ μ΄κ²μ ν
μ΄λΈμ²λΌ μ¬κΈ°κ³ λ°μ μλ select
κ° μ€ν
with
Subquery
μ λ κΉλνκ³ λ³΄κΈ° νΈνκ² μ 리ν μ μλ€.
with table1 as (
... ... ...
), table2 as (
... ... ...
)
select * from ...
Subquery
λ₯Ό νλμ λ€λ₯Έ ν
μ΄λΈλ‘ λ§λ€μ΄μ€λ€.