๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
6๏ธโƒฃ SQL/SQL ์ •๋ฆฌ

[MySQL] INNER, OUTER JOIN ์ •๋ฆฌ

by seolhee2750 2022. 2. 3.

(์„ค๋ช…์— ์“ฐ์ผ ํ…Œ์ด๋ธ” ์˜ˆ์‹œ)

TABLE_A

ID ALPHABET
1 abc
2 abcd
3 abcde

TABLE_B

ID NUM
2 10
3 20
4 30

 


๐Ÿ“ INNER JOIN

๊ต์ง‘ํ•ฉ์„ ์˜๋ฏธํ•˜๊ณ , ๊ณตํ†ต ๋ถ€๋ถ„๋งŒ SELECT๋œ๋‹ค.

SELECT A.ID, A.ALPHABET, A.NUM
FROM TABLE_A AS A
INNER JOIN TABLE_B AS B
ON A.ID = B.ID

 

ID ALPHABET NUM
2 abcd 10
3 abcde 20

 

๐Ÿ“ LEFT OUTER JOIN

(1) ๊ณตํ†ต ๋ถ€๋ถ„ ํฌํ•จ, ์กฐ์ธ ๊ธฐ์ค€ ์™ผ์ชฝ ํ…Œ์ด๋ธ”์˜ ์ „๋ถ€๋ฅผ SELECT ํ•œ๋‹ค.

SELECT A.ID, A.ALPHABET, A.NUM
FROM TABLE_A AS A
LEFT OUTER JOIN TABLE_B AS B
ON A.ID = B.ID
ID ALPHABET NUM
1 abc NULL
2 abcd 10
3 abcde 20

 

(2) ๊ณตํ†ต ๋ถ€๋ถ„ ์ œ์™ธ, ์กฐ์ธ ๊ธฐ์ค€ ์™ผ์ชฝ ํ…Œ์ด๋ธ”์˜ ์ „๋ถ€๋ฅผ SELECT ํ•œ๋‹ค.

SELECT A.ID, A.ALPHABET, A.NUM
FROM TABLE_A AS A
LEFT OUTER JOIN TABLE_B AS B
ON A.ID = B.ID
WHERE B.ID IS NULL
ID ALPHABET NUM
1 abc NULL

 

๐Ÿ“ RIGHT OUTER JOIN

(1) ๊ณตํ†ต ๋ถ€๋ถ„ ํฌํ•จ, ์กฐ์ธ ๊ธฐ์ค€ ์˜ค๋ฅธ์ชฝ ํ…Œ์ด๋ธ”์˜ ์ „๋ถ€๋ฅผ SELECT ํ•œ๋‹ค.

SELECT A.ID, A.ALPHABET, A.NUM
FROM TABLE_A AS A
RIGHT OUTER JOIN TABLE_B AS B
ON A.ID = B.ID
ID ALPHABET NUM
2 abcd 10
3 abcde 20
4 NULL 30

 

(2) ๊ณตํ†ต ๋ถ€๋ถ„ ์ œ์™ธ, ์กฐ์ธ ๊ธฐ์ค€ ์˜ค๋ฅธ์ชฝ ํ…Œ์ด๋ธ”์˜ ์ „๋ถ€๋ฅผ SELECT ํ•œ๋‹ค.

SELECT A.ID, A.ALPHABET, A.NUM
FROM TABLE_A AS A
RIGHT OUTER JOIN TABLE_B AS B
ON A.ID = B.ID
WHERE A.ID IS NULL
ID ALPHABET NUM
4 NULL 30

 

๐Ÿ“ FULL OUTER JOIN

(1) ์ „๋ถ€ SELECT

SELECT A.ID, A.ALPHABET, A.NUM
FROM TABLE_A AS A
FULL OUTER JOIN TABLE_B AS B
ON A.ID = B.ID
ID ALPHABET NUM
1 abc NULL
2 abcd 10
3 abcde 20
4 NULL 30

 

(2) ๊ณตํ†ต ๋ถ€๋ถ„๋งŒ ์ œ์™ธํ•œ ์ „๋ถ€๋ฅผ SELECT

SELECT A.ID, A.ALPHABET, A.NUM
FROM TABLE_A AS A
FULL OUTER JOIN TABLE_B AS B
ON A.ID = B.ID
WHERE A.ID IS NULL OR B.ID IS NULL
ID ALPHABET NUM
1 abc NULL
4 NULL 30

 


๐Ÿ– ํ•ต์‹ฌ ํฌ์ธํŠธ

  1. INNER๋Š” ๊ณตํ†ต๋œ ๋ถ€๋ถ„๋งŒ ๊ฐ€์ง€๋ฏ€๋กœ, NULL์„ ๊ฐ€์งˆ ์ˆ˜ ์—†๋‹ค.
  2. LEFT๋Š” ์˜ค๋ฅธ์ชฝ ํ…Œ์ด๋ธ”์—๋งŒ NULL์ด ์žˆ์„ ์ˆ˜ ์žˆ๊ณ ,
    RIGHT๋Š” ์™ผ์ชฝ ํ…Œ์ด๋ธ”์—๋งŒ NULL์ด ์žˆ์„ ์ˆ˜ ์žˆ์œผ๋ฉฐ,
    FULL์€ ์–‘์ชฝ ํ…Œ์ด๋ธ” ๋ชจ๋‘์— NULL์ด ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค.
    ๋”ฐ๋ผ์„œ, ํ•œ ํ…Œ์ด๋ธ”์—๋งŒ ์žˆ๊ณ  ํ•œ ํ…Œ์ด๋ธ”์—๋Š” ์—†๋Š” ๊ฒƒ์„ ์ฐพ์•„์•ผ ํ•  ๋•Œ๋Š”
    LEFT๋‚˜ RIGHT์„ ์จ์„œ, NULL์„ ์ฐพ์œผ๋ฉด ๋œ๋‹ค.
  3. LEFT์™€ RIGHT๋Š” ๋ฐฉํ–ฅ๋งŒ ๋ฐ”๋€ ๊ฒƒ์ด๋‹ˆ, ํ•œ ๊ฐ€์ง€๋งŒ ๊ณต๋ถ€ํ•ด์„œ ๋Œ๋ ค์“ฐ์ž.

๋Œ“๊ธ€