์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋ณดํ˜ธ์†Œ์—์„œ ์ค‘์„ฑํ™”ํ•œ ๋™๋ฌผ (SQL/JOIN)

PROGRAMMING/Database

by koharin 2021. 1. 30. 12:41

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

๐Ÿ’ป MYSQL ์ œ์ถœ์ฝ”๋“œ


SELECT B.ANIMAL_ID, B.ANIMAL_TYPE, B.NAME // ์กฐํšŒํ•  COLUMN
FROM ANIMAL_INS A
RIGHT OUTER JOIN ANIMAL_OUTS B
ON A.ANIMAL_ID = B.ANIMAL_ID // ๋™์ผํ•œ ๋™๋ฌผ, ์ฆ‰ ANIMAL_ID์—์„œ
WHERE A.SEX_UPON_INTAKE LIKE '%Intact%' AND B.SEX_UPON_OUTCOME NOT LIKE '%Intact%' // A์—๋Š” Intact๊ฐ€ ์žˆ๋Š”๋ฐ(์ค‘์„ฑํ™” X) B์—๋Š” Intact๊ฐ€ ์—†๋Š”(์ค‘์„ฑํ™” O) ์กฐ๊ฑด
ORDER BY ANIMAL_ID ASC; // ์ด๋ฆ„ ์ˆœ ์ •๋ ฌ

 

 

๐Ÿ“ ๋ฌธ์ œํ’€์ด ๊ณผ์ •


  • ๋“ค์–ด์˜ฌ ๋•Œ ์ค‘์„ฑํ™” X, ๋‚˜๊ฐˆ ๋•Œ ์ค‘์„ฑํ™” O: RIGHT EXCLUSIVE -> TABLE B์—์„œ ANIMAL_ID์„ ์กฐํšŒํ–ˆ์„ ๋•Œ, WHERE์—์„œ ์ค€ ์กฐ๊ฑด์ด ๋™์ผํ•œ ANIMAL_ID๋ฅผ ๊ฐ–๋Š” TABLE A์˜ ๋ฐ์ดํ„ฐ์™€ ๋งค์นญํ•ด์„œ ์ผ์น˜ํ•˜๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ B์— ์žˆ๋Š” ANIMAL_ID ๋ฐ ์นผ๋Ÿผ๋“ค์„ ๊ฐ€์ ธ์˜จ๋‹ค.

  • ์ค‘์„ฑํ™” ์—ฌ๋ถ€: ์ค‘์„ฑํ™” ํ–ˆ์„ ๋•Œ Female์˜ ๊ฒฝ์šฐ Spayed Female์ด๊ณ , Male์˜ ๊ฒฝ์šฐ Neutral์ด๋‹ค. ์ค‘์„ฑํ™”ํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ์—๋Š” Female์ด๋‚˜ Male์ด๋‚˜ ๋™์ผํ•˜๊ฒŒ Intact๊ฐ€ ๋ถ™์œผ๋ฏ€๋กœ, A์˜ SEX_UPON_INTAKE์— Intact๊ฐ€ ์žˆ๋Š”๋ฐ B์˜ SEX_UPON_OUTCOME์—๋Š” Intact๊ฐ€ ์—†๋Š” ์กฐ๊ฑด์„ ์กฐํšŒํ•œ๋‹ค. => Intact ๋ฌธ์ž์—ด ์œ ๋ฌด๋Š” LIKE์™€ NOT LIKE

  • ์•„์ด๋”” ์ˆœ ์ •๋ ฌ: ORDER BY ANIMAL_ID ASC

SELECT B.ANIMAL_ID, B.ANIMAL_TYPE, B.NAME, B.SEX_UPON_OUTCOME // ๊ฒฐ๊ณผ๋ฅผ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด B.SEX_UPON_OUTCOME๋„ ์คฌ๋‹ค
FROM ANIMAL_INS A
RIGHT OUTER JOIN ANIMAL_OUTS B
ON A.ANIMAL_ID = B.ANIMAL_ID
WHERE A.SEX_UPON_INTAKE LIKE '%Intact%' AND B.SEX_UPON_OUTCOME NOT LIKE '%Intact%'
ORDER BY ANIMAL_ID ASC;

  • ๋ฌธ์ œ์—์„œ๋Š” SEX_UPON_OUTCOME์„ ์กฐํšŒํ•˜์ง€ ์•Š๋Š”๋ฐ, ๋ฌธ์ œ๋ฅผ ํ‘ธ๋Š” ๊ณผ์ •์—์„œ ์‹คํ–‰ํ–ˆ์„ ๋•Œ ์ œ๋Œ€๋กœ ๋‚˜์˜ค๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ๋„ฃ์–ด๋ดค๋‹ค.

728x90
๋ฐ˜์‘ํ˜•

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ