SQL

SQL ํ…Œ์ด๋ธ” ๋ถ™์ด๊ธฐ inner join / left join / NULL

GABOJOK 2023. 9. 23. 23:53

join

๐Ÿ‘‰  ์„œ๋กœ ๋‹ค๋ฅธ 2๊ฐœ์˜ ํ…Œ์ด๋ธ” ๋ถ™์—ฌ์„œ ํ•˜๋‚˜์˜ ํ…Œ์ด๋ธ” ์ฒ˜๋Ÿผ ๋ณด๋Š”๊ฑฐ.

๐Ÿ‘‰  ๋ถ™์ด๋ ค๋Š” ๊ฐ๊ฐ์˜ ํ…Œ์ด๋ธ”์— ๊ณตํ†ต ์ •๋ณด๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์—ฐ๊ฒฐํ•œ๋‹ค. 

๐Ÿ‘‰  Join์˜ ์ข…๋ฅ˜๊ฐ€ ๋งŽ์Œ.

๐Ÿ‘‰   Inner Join / Left Join / Right Outer Join / Full Outer Join / Cross Join / Self Join 

 

 

 

Inner Join

๐Ÿ‘‰   ๋‘ ํ…Œ์ด๋ธ” ๋ชจ๋‘ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋งŒ ๋ณด์—ฌ์ค€๋‹ค.

๐Ÿ‘‰   ํ•œ๋งˆ๋””๋กœ ๊ต์ง‘ํ•ฉ.

 

inner join

select * from users u
inner join point_users p
on u.user_id = p.user_id

 

 on ์„ ์ด์šฉํ•ด์„œ joinํ•œ๋‹ค.

๐Ÿ‘‰  ๊ณตํ†ต๋œ ์ •๋ณด๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ถ™์—ฌ์•ผ ํ•˜๋‹ˆ๊นŒ ๋‘ ํ…Œ์ด๋ธ” ๋ชจ๋‘ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์ •๋ณด์ธ user_id๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ถ™์ธ๊ฑฐ.  

๐Ÿ‘‰  ๋์— u, p ์ด๋Ÿฐ๊ฑฐ๋Š” alias ์ด๋‹ค. ์ฆ‰ ๋ณ„์นญ.

 

 

 

 

Left Join

 

๐Ÿ‘‰   ์™ผ์ชฝ ํ…Œ์ด๋ธ” ๊ธฐ์ค€์œผ๋กœ ๋‹ค๋ฅธ ํ…Œ์ด๋ธ” ๋ถ™์ธ๋‹ค๋Š” ๋œป

๐Ÿ‘‰   ์™ผ์ชฝ ํ…Œ์ด๋ธ”์˜ ๋ฐ์ดํ„ฐ๋Š” ๋ชจ๋‘ ์ถœ๋ ฅ๋จ.

๐Ÿ‘‰   ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์œผ๋ฉด NULL์„ ๋„ฃ์–ด์„œ ๋ณด์—ฌ์ค€๋‹ค.

๐Ÿ‘‰   ์ •๋ณด๊ฐ€ ์—†๋Š” ๊ฒƒ๊นŒ์ง€ ํฌํ•จํ•ด์„œ ํ†ต๊ณ„๋ฅผ ๋‚ด๊ณ  ์‹ถ์„๋•Œ ์‚ฌ์šฉ.

select * from users u
left join point_users p
on u.user_id = p.user_id

 

 

 

 

Full Outer Join

๐Ÿ‘‰   ๋‘ ํ…Œ์ด๋ธ”์˜ ๋ฐ์ดํ„ฐ ๋ชจ๋‘ ์ถœ๋ ฅ๋œ๋‹ค

๐Ÿ‘‰   Right Join ๊ณผ Left Join ์˜ ๊ฒฐ๊ณผ๋ฅผ ํ•ฉ์ง‘ํ•ฉ ํ•œ ๊ฒƒ๊ณผ ๊ฐ™๋‹ค.

๐Ÿ‘‰   Outer ํ‚ค์›Œ๋“œ ์ƒ๋žต ๊ฐ€๋Šฅํ•˜๋‹ค. 

๐Ÿ‘‰   ์ค‘๋ณต๋˜๋Š” ํ‚ค์›Œ๋“œ๋Š” ์‚ญ์ œํ•จ.

 

 

 

FULL OUTER JOIN ์— ๋Œ€ํ•œ ๋‚ด์šฉ ์•„๋ž˜์—์„œ ๊ฐ€์ ธ์˜ด

https://limkydev.tistory.com/144

 

[DataBase] OUTER JOIN (์™ธ๋ถ€์กฐ์ธ) LEFT,RIGHT,FULL JOIN

OUTER JOIN(์™ธ๋ถ€์กฐ์ธ) INNER(๋‚ด๋ถ€) JOIN ๊ณผ ๋Œ€๋น„ํ•˜์—ฌ OUTER(์™ธ๋ถ€) JOIN์ด๋ผ๊ณ  ๋ถˆ๋ฆฌ๋ฉฐ, JOIN ์กฐ๊ฑด์—์„œ ๋™์ผํ•œ ๊ฐ’์ด ์—†๋Š” ํ–‰๋„ ๋ฐ˜ํ™˜ํ•  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ์ฆ‰ A, B ํ…Œ์ด๋ธ”์„ JOIN ํ•  ๊ฒฝ์šฐ, ์กฐ๊ฑด์— ๋งž์ง€ ์•Š๋Š” ๋ฐ์ดํ„ฐ๋„

limkydev.tistory.com

 

 

 

 

 

join ์„ ๋‘๋ฒˆ ํ•ด์•ผํ•  ๋•Œ

select * for courses co
inner join checkins ch on co.course_id = ch.course_id 
inner join orders o on ch.user_id = o.user_id

 

 

 

NULL ์˜ ๊ฐ’๋งŒ ์ทจํ•˜๊ธฐ 

๐Ÿ‘‰   where ํ•„๋“œ๋ช…  is NULL

select * from users u 
left join point_users pu 
on pu.user_id = u.user_id 
where pu.point_user_id is null

 

 

 

NULL ์ด ์•„๋‹Œ ๊ฐ’๋งŒ ์ทจํ•˜๊ธฐ.

๐Ÿ‘‰   where ํ•„๋“œ๋ช…  is not NULL

 

โŽโŽโŽโŽโŽ

where  ํ•„๋“œ๋ช…  = NULL  ๐Ÿ‘ˆ ๋ฐ์ดํ„ฐ๊ฐ€ ๋‚˜์˜ค์ง€ ์•Š๋Š”๋‹ค. 

select * from users u 
left join point_users pu 
on pu.user_id = u.user_id 
where pu.point_user_id is not null