๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
6๏ธโƒฃ SQL/Problem Solving

[MySQL] Programmers Lv.3 ์ „์ฒด ๋ฌธ์ œ ํ’€์ด

by seolhee2750 2022. 2. 2.
์—†์–ด์ง„ ๊ธฐ๋ก ์ฐพ๊ธฐ
-- join ๋ฏธ์‚ฌ์šฉ
SELECT ANIMAL_ID, NAME
FROM ANIMAL_OUTS
WHERE ANIMAL_ID NOT IN (
SELECT ANIMAL_ID
FROM ANIMAL_INS)

-- join ์‚ฌ์šฉ
SELECT OUTS.ANIMAL_ID, OUTS.NAME
FROM ANIMAL_OUTS AS OUTS
LEFT OUTER JOIN ANIMAL_INS AS INS
ON OUTS.ANIMAL_ID = INS.ANIMAL_ID
WHERE INS.ANIMAL_ID IS NULL
ORDER BY OUTS.ANIMAL_ID

๐Ÿ– JOIN ์‚ฌ์šฉํ•  ๋•Œ๋Š” ๊ฐ ํ…Œ์ด๋ธ”์— ์ด๋ฆ„ ๋ถ™์—ฌ์„œ ์จ์ฃผ๊ณ , ON์œผ๋กœ ์™ธ๋ž˜ํ‚ค ๋งž์ถฐ์ฃผ๊ธฐ

๐Ÿ– OUTER JOIN ์‚ฌ์šฉํ•˜๋ฉด ์„œ๋กœ ์–ด๋–ค ์ฐจ์ด๊ฐ€ ์žˆ๋Š”์ง€ ์•Œ ์ˆ˜ ์žˆ์Œ

(https://seolhee2750.tistory.com/175)

 

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

(์„ค๋ช…์— ์“ฐ์ผ ํ…Œ์ด๋ธ” ์˜ˆ์‹œ) TABLE_A ID ALPHBET 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 A..

seolhee2750.tistory.com

 

์˜ค๋žœ ๊ธฐ๊ฐ„ ๋ณดํ˜ธํ•œ ๋™๋ฌผ(1)
-- join ๋ฏธ์‚ฌ์šฉ
SELECT NAME, DATETIME
FROM ANIMAL_INS
WHERE ANIMAL_ID NOT IN (
SELECT ANIMAL_ID
FROM ANIMAL_OUTS)
ORDER BY DATETIME
LIMIT 3

-- join ์‚ฌ์šฉ
SELECT INS.NAME, INS.DATETIME
FROM ANIMAL_INS AS INS
LEFT OUTER JOIN ANIMAL_OUTS AS OUTS
ON INS.ANIMAL_ID = OUTS.ANIMAL_ID
WHERE OUTS.ANIMAL_ID IS NULL
ORDER BY DATETIME
LIMIT 3

 

์˜ค๋žœ ๊ธฐ๊ฐ„ ๋ณดํ˜ธํ•œ ๋™๋ฌผ(2)
SELECT OUTS.ANIMAL_ID, OUTS.NAME
FROM ANIMAL_INS AS INS
JOIN ANIMAL_OUTS AS OUTS
ON INS.ANIMAL_ID = OUTS.ANIMAL_ID
ORDER BY OUTS.DATETIME - INS.DATETIME DESC
LIMIT 2

 

์žˆ์—ˆ๋Š”๋ฐ์š” ์—†์—ˆ์Šต๋‹ˆ๋‹ค
SELECT INS.ANIMAL_ID, INS.NAME
FROM ANIMAL_INS AS INS
JOIN ANIMAL_OUTS AS OUTS
ON INS.ANIMAL_ID = OUTS.ANIMAL_ID
WHERE INS.DATETIME > OUTS.DATETIME
ORDER BY INS.DATETIME

 

ํ—ค๋น„ ์œ ์ €๊ฐ€ ์†Œ์œ ํ•œ ์žฅ์†Œ
SELECT ID, NAME, HOST_ID
FROM PLACES
WHERE HOST_ID IN (
SELECT HOST_ID
FROM PLACES
GROUP BY HOST_ID
HAVING COUNT(HOST_ID) >= 2)
ORDER BY ID

 

๋Œ“๊ธ€