[SQL] Subquery, with

CountryGirlΒ·2023λ…„ 6μ›” 3일
0

SQL

λͺ©λ‘ 보기
6/7
post-thumbnail

πŸ“Œ 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 λ₯Ό ν•˜λ‚˜μ˜ λ‹€λ₯Έ ν…Œμ΄λΈ”λ‘œ λ§Œλ“€μ–΄μ€€λ‹€.

profile
πŸ’»πŸŒΎμ‹œκ³¨μ†Œλ…€μ˜ 엉망징창 개발 μ„±μž₯μΌμ§€πŸŒΎπŸ’» (2023.05.23 ~)

0개의 λŒ“κΈ€