ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๋ฌธ์ œ ํ’€์ด

 ๊ฐ ๋ฌธ์ œ์—์„œ๋Š” `ANIMAL_INS`, `ANIMAL_OUT`์™€ ๊ฐ™์ด ๋™๋ฌผ์ด ๋ณดํ˜ธ์†Œ์— ๋“ค์–ด์˜จ ์ •๋ณด์— ๋Œ€ํ•œ ํ…Œ์ด๋ธ”๊ณผ ๋ณดํ˜ธ์†Œ์—์„œ ๋‚˜๊ฐ„ ๊ฒฝ์šฐ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๊ฐ€์ง„ ํ…Œ์ด๋ธ”์ด ์ฃผ์–ด์ง„๋‹ค. ์ด๋•Œ ๋ฌธ์ œ์—์„œ๋Š” `JOIN`์„ ํ†ตํ•ด ๋‘ ๊ฐ€์ง€ ํ…Œ์ด๋ธ”์„ ํ•จ๊ป˜ ์กฐํšŒํ•˜์—ฌ ์›ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ๊ฐ€ ์ถœ์ œ๋œ๋‹ค. `JOIN`์„ ์ดํ•ดํ•˜๊ณ , `ON`, `WHERE`๋ฅผ ์ ์ ˆํžˆ ์ด์šฉํ•˜๋ฉด ๋ฌธ์ œ๋ฅผ ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

์—†์–ด์ง„ ๊ธฐ๋ก ์ฐพ๊ธฐ

SELECT OUTS.ANIMAL_ID, OUTS.NAME
FROM ANIMAL_OUTS OUTS
LEFT JOIN ANIMAL_INS INS
ON OUTS.ANIMAL_ID = INS.ANIMAL_ID
WHERE INS.ANIMAL_ID IS NULL
ORDER BY OUTS.ANIMAL_ID

 ์ž…์–‘์„ ๊ฐ„ ๊ธฐ๋ก์€ ์žˆ์ง€๋งŒ, ๋ณดํ˜ธ์†Œ์— ๋“ค์–ด์˜จ ๊ธฐ๋ก์ด ์—†๋Š” ๊ฒฝ์šฐ๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. `ON OUTS.ANIMAL_ID = INS.ANIMAL_ID`๋ฅผ ํ†ตํ•ด `ANIMAL_ID`๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ , ์ด๊ฒƒ์ด `NULL`์ธ ๊ฒฝ์šฐ๊ฐ€ ์ •๋‹ต์ด๋‹ค.

 

์žˆ์—ˆ๋Š”๋ฐ์š” ์—†์—ˆ์Šต๋‹ˆ๋‹ค

SELECT INS.ANIMAL_ID, INS.NAME
FROM ANIMAL_OUTS OUTS, ANIMAL_INS INS
WHERE INS.DATETIME > OUTS.DATETIME AND INS.ANIMAL_ID = OUTS.ANIMAL_ID
ORDER BY INS.DATETIME

 `JOIN`์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ ๋„ `WHERE`๋ฅผ ํ†ตํ•ด ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ฌธ์ œ์—์„œ ๋ณดํ˜ธ ์‹œ์ž‘์ผ๋ณด๋‹ค ์ž…์–‘์ผ์ด ๋น ๋ฅธ ๊ฒฝ์šฐ๋ฅผ ์ฐพ์œผ๋ผ๊ณ  ํ•˜์˜€์œผ๋‹ˆ `INS.DATETIME > OUTSDATETIME`์ด ๋œ๋‹ค.

 

 ์˜ค๋žœ ๊ธฐ๊ฐ„ ๋ณดํ˜ธํ•œ ๋™๋ฌผ(1)

SELECT INS.NAME, INS.DATETIME
FROM ANIMAL_INS INS
LEFT JOIN ANIMAL_OUTS OUTS
ON OUTS.ANIMAL_ID = INS.ANIMAL_ID
WHERE OUTS.ANIMAL_ID IS NULL
ORDER BY INS.DATETIME
LIMIT 3

 `JOIN`์„ ํ•œ ํ›„์— `OUTS.ANIMAL_ID`๊ฐ€ `NULL`์ด๋ผ๋ฉด ์ž…์–‘์„ ๊ฐ€์ง€ ์•Š์€ ๋™๋ฌผ์ด๋‹ค. ๋”ฐ๋ผ์„œ ์ด ๊ฒฐ๊ณผ๋ฅผ ์ •๋ ฌํ•˜๊ณ  `LIMIT 3`์„ ํ†ตํ•ด ์ถœ๋ ฅ ์ œํ•œ์„ ๋‘๋ฉด ๋ฌธ์ œ์—์„œ ์ฐพ๊ณ ์ž ํ•˜๋Š” ๋‹ต์ด ๋œ๋‹ค.

 

๋ณดํ˜ธ์†Œ์—์„œ ์ค‘์„ฑํ™”ํ•œ ๋™๋ฌผ

SELECT INS.ANIMAL_ID, INS.ANIMAL_TYPE, INS.NAME
FROM ANIMAL_INS INS
RIGHT JOIN ANIMAL_OUTS OUTS
ON INS.ANIMAL_ID = OUTS.ANIMAL_ID
WHERE INS.SEX_UPON_INTAKE != OUTS.SEX_UPON_OUTCOME
ORDER BY INS.ANIMAL_ID

 ์ฒ˜์Œ์—๋Š” `INS.SEX_UPON_INTAKE LIKE '%Intact%' AND OUTS.SEX_UPON_OUTCOME NOT LIKE '%Intact%'`๋กœ ์ž‘์„ฑํ•˜์˜€๋‹ค. ๋‹ค์‹œ ์ƒ๊ฐํ•ด๋ณด๋ฉด `INS.SEX_UPON_INTAKE != OUTS.SEX_UPON_OUTCOME`์œผ๋กœ ๊ฐ„๋žตํžˆ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€