[SQL] left join, inner join, union

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

SQL

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

πŸ“Œ join μ΄λž€ ?

두 ν…Œμ΄λΈ”μ˜ κ³΅ν†΅λœ 정보(key)λ₯Ό κΈ°μ€€μœΌλ‘œ ν…Œμ΄λΈ”μ„ μ—°κ²°ν•΄μ„œ ν•œ ν…Œμ΄λΈ”μ²˜λŸΌ λ³Ό 수 μžˆλ„λ‘ ν•˜λŠ” 것
πŸ‘‰ μ›ν•˜λŠ” 정보가 A에도 있고 B에도 μžˆμ„ λ•Œ μ„œλ‘œ λ¬Άμ–΄μ„œ 확인할 수 μžˆλ‹€.


πŸ“Œ left join

'AλΌλŠ” ν…Œμ΄λΈ”κ³Ό BλΌλŠ” ν…Œμ΄λΈ”μ˜ κ³΅ν†΅λœ 정보(key)λ₯Ό μ—°κ²°ν•˜μ—¬ AλΌλŠ” ν…Œμ΄λΈ”μ— BλΌλŠ” ν…Œμ΄λΈ”μ„ 뢙인닀'λŠ” λŠλ‚Œ(?)πŸ’‘

μ–΄λ–€ λ°μ΄ν„°λŠ” λͺ¨λ“  ν•„λ“œκ°€ μ±„μ›Œμ Έμžˆμ§€λ§Œ, μ–΄λ–€ λ°μ΄ν„°λŠ” λͺ¨λ“  ν•„λ“œκ°€ μ±„μ›Œμ Έμžˆμ§€ μ•Šκ³  λΉ„μ–΄μžˆλŠ” ν•„λ“œκ°€ μ‘΄μž¬ν•  λ•Œ, μ •μƒμ μœΌλ‘œ 데이터가 좜λ ₯λ˜μ§€ μ•Šμ„ 수 μžˆλ‹€.

select ν•„λ“œλͺ… from ν…Œμ΄λΈ”λͺ…(μ™Όμͺ½) 
left join μ™Όμͺ½ν…Œμ΄λΈ”에 뢙일 λ‹€λ₯Έ ν…Œμ΄λΈ”
on μ™Όμͺ½ν…Œμ΄λΈ”μ˜ ν•„λ“œ = 였λ₯Έμͺ½ν…Œμ΄λΈ”μ˜ ν•„λ“œ		// κ³΅ν†΅λœ 정보
select * from A_table a
left join B_table b
on a.number = b.number

πŸ“Œ inner join

'AλΌλŠ” ν…Œμ΄λΈ”κ³Ό BλΌλŠ” ν…Œμ΄λΈ”μ˜ κ³΅ν†΅λœ 정보(key)만 묢은 ꡐ집합 λŠλ‚Œ(?)πŸ’‘

inner join 을 μ‚¬μš©ν•˜κ²Œ 되면 NULL (λΉ„μ–΄μžˆλŠ” ν•„λ“œκ°€ μžˆλŠ” 데이터) 이 μ—†λ‹€ !

inner join 은 κ΅μ§‘ν•©μ΄μ–΄μ„œ A와 B λͺ¨λ“  ν…Œμ΄λΈ”μ΄ 가지고 μžˆλŠ” 데이터λ₯Ό λ¬Άκ³ , left join λŠ” λ¬Όλ‘  κ³΅ν†΅λœ 데이터도 μžˆμ§€λ§Œ ν•œμͺ½μ—λ§Œ μžˆλŠ” 데이터가 μžˆμ–΄ NULL 이 μ‘΄μž¬ν•  수 μžˆλ‹€.

select ν•„λ“œλͺ… from ν…Œμ΄λΈ”λͺ…(μ™Όμͺ½) 
inner join μ™Όμͺ½ν…Œμ΄λΈ”에 뢙일 λ‹€λ₯Έ ν…Œμ΄λΈ”
on μ™Όμͺ½ν…Œμ΄λΈ”μ˜ ν•„λ“œ = 였λ₯Έμͺ½ν…Œμ΄λΈ”μ˜ ν•„λ“œ		// κ³΅ν†΅λœ 정보
select * from A_table a
inner join B_table b
on a.number = b.number

πŸ“Œ union

SELECTλ₯Ό λ‘λ²ˆν•˜μ§€ μ•Šκ³  ν•œ λ²ˆμ— λͺ¨μ•„μ„œ 보고싢은 κ²½μš°μ— μ‚¬μš©ν•œλ‹€.
ex) 11μ›” 데이터와 12μ›” 데이터λ₯Ό ν•œ λ²ˆμ— 보고싢을 λ•Œ.

(
select '7 ' as month, c.title, c2.week, count(*) as cnt 
from checkins c2 
inner join courses c on c2.course_id = c.course_id
inner join orders o on o.user_id = c2.user_id
where o.created_at < '2012-08-01'
group by c2.course_id, c2.week
order by c2.course_id, c2.week
)
union all (
  select '8 ' as month, c.title, c2.week, count(*) as cnt 
  from checkins c2  
  inner join courses c on c2.course_id = c.course_id
  inner join orders o on o.user_id = c2.user_id
  where o.created_at > '2012-08-01'
  group by c2.course_id, c2.week
  order by c2.course_id, c2.week
)

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

0개의 λŒ“κΈ€