" MYSQL ์ฝ”๋”ฉํ…Œ์ŠคํŠธ์—ฐ์Šต: REGEXP ์ •๊ทœํ‘œํ˜„์‹
๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
ํ˜„์—…๊ด‘๊ณ ์ธ/๊ฐ์ข…๊ฟ€ํŒ

MYSQL ์ฝ”๋”ฉํ…Œ์ŠคํŠธ์—ฐ์Šต: REGEXP ์ •๊ทœํ‘œํ˜„์‹

by ๋…๋”˜ 2021. 2. 16.
728x90
๋ฐ˜์‘ํ˜•
# -- ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”
# SELECT I.ANIMAL_ID, I.NAME,I.SEX_UPON_INTAKE
# FROM ANIMAL_INS I
# WHERE I.NAME IN ('Lucy','Ella','Pickle','Rogan','Sabrina','Mitty')
# ORDER BY ANIMAL_ID ASC;

SELECT I.ANIMAL_ID, I.NAME,I.SEX_UPON_INTAKE 
FROM ANIMAL_INS I
WHERE I.NAME REGEXP '^(Lucy|Ella|Pickle|Rogan|Sabrina|Mitty)$'
ORDER BY I.ANIMAL_ID ASC;
 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋ฃจ์‹œ์™€ ์—˜๋ผ ์ฐพ๊ธฐ

ANIMAL_INS ํ…Œ์ด๋ธ”์€ ๋™๋ฌผ ๋ณดํ˜ธ์†Œ์— ๋“ค์–ด์˜จ ๋™๋ฌผ์˜ ์ •๋ณด๋ฅผ ๋‹ด์€ ํ…Œ์ด๋ธ”์ž…๋‹ˆ๋‹ค. ANIMAL_INS ํ…Œ์ด๋ธ” ๊ตฌ์กฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์œผ๋ฉฐ, ANIMAL_ID, ANIMAL_TYPE, DATETIME, INTAKE_CONDITION, NAME, SEX_UPON_INTAKE๋Š” ๊ฐ๊ฐ ๋™๋ฌผ์˜ ์•„์ด๋””

programmers.co.kr

ํ•ด๋‹น ๊ธ€์€ Programmers ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต์„ ํ† ๋Œ€๋กœ MYSQL ๋กœ ์ž‘์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

 


Q ๋ฌธ์ œ: Lucy ~ Mitty ํ•ด๋‹น ๋™๋ฌผ์˜ ์ด๋ฆ„์ด ํฌํ•จ๋˜์–ด ์žˆ๋Š” ๋™๋ฌผ ์นœ๊ตฌ๋“ค์„ ์ฐพ์•„๋ผ. 

A ์ •๋‹ต์ฝ”๋“œ:

# -- ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”
# SELECT I.ANIMAL_ID, I.NAME,I.SEX_UPON_INTAKE
# FROM ANIMAL_INS I
# WHERE I.NAME IN ('Lucy','Ella','Pickle','Rogan','Sabrina','Mitty')
# ORDER BY ANIMAL_ID ASC;

SELECT I.ANIMAL_ID, I.NAME,I.SEX_UPON_INTAKE 
FROM ANIMAL_INS I
WHERE I.NAME REGEXP '^(Lucy|Ella|Pickle|Rogan|Sabrina|Mitty)$'
ORDER BY I.ANIMAL_ID ASC;

REGEXP ์ •๊ทœํ‘œํ˜„์‹

Regular Expression์˜ ์•ฝ์ž๋กœ  ๋ฌธ์ž์—ด์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ• ์ค‘์˜ ํ•˜๋‚˜๋กœ ํŠน์ •ํ•œ ์กฐ๊ฑด์˜ ๋ฌธ์ž๋ฅผ '๊ฒ€์ƒ‰'ํ•˜๊ฑฐ๋‚˜ '์น˜ํ™˜'ํ•˜๋Š” ๊ณผ์ •์„ ๋งค์šฐ ๊ฐ„ํŽธํ•˜๊ฒŒ ์ฒ˜๋ฆฌ ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋Š” ์ˆ˜๋‹จ์ด๋‹ค. 

# -- ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”

# ์ปฌ๋Ÿผ๋ช… ์ค‘ Lucy ~ Mitty ๊ฐ€ ํฌํ•จ๋œ ๋ชจ๋“  ์ด๋ฆ„์„ ์กฐํšŒ 
WHERE I.NAME REGEXP 'Lucy|Ella|Pickle|Rogan|Sabrina|Mitty'

# ์ปฌ๋Ÿผ๋ช… ์ค‘ Lucy ~ Mitty ์ผ์น˜ํ•˜๋Š” ์ด๋ฆ„์„ ์กฐํšŒ 
WHERE I.NAME REGEXP '^(Lucy|Ella|Pickle|Rogan|Sabrina|Mitty)$'

 1:1 ๋งค์นญ์ด ๋˜๋ ค๋ฉด ์‹œ์ž‘์—๋Š” ^ ๋์—๋Š” $๋ฅผ ๋ถ™์—ฌ์ค˜์•ผํ•œ๋‹ค.

๊ทธ๋ ‡์ง€์•Š๊ณ  ์œ„์ฒ˜๋Ÿผ ์ฟผ๋ฆฌ๋ฌธ์„ ์ž‘์„ฑํ•œ๋‹ค๋ฉด LLLucy, Ellaaaa ์™€ ๊ฐ™์€ ์ด๋ฆ„์ด ์กด์žฌํ•œ๋‹ค๋ฉด ๋ชจ๋‘ ์ถœ๋ ฅ์ด ๋ ๊ฒƒ์ด๋‹ค.

 

ํ‘œํ˜„์‹ ์˜๋ฏธ
^ ๋ฌธ์žA ๋ฌธ์ž์—ด์˜ ์‹œ์ž‘์„ ํ‘œํ˜„   (์„ค๋ช…) ๋ฌธ์ž A๋กœ ์‹œ์ž‘๋˜๋Š” ๋ฌธ์ž ์กฐํšŒ
   ๋ฌธ์žA & ๋ฌธ์ž์—ด์˜ ๋์„ ํ‘œํ˜„      (์„ค๋ช…) ๋ฌธ์ž A๋กœ ๋๋‚˜๋Š” ๋ฌธ์ž ์กฐํšŒ 
^ ๋ฌธ์žA๋ฌธ์žB & (์„ค๋ช…) ๋ฌธ์žA๋กœ ์‹œ์ž‘ํ•˜๋ฉฐ ๋ฌธ์žB๋กœ ๋๋‚˜๋Š” ๋ฌธ์ž ์กฐํšŒ
๋ฌธ์žA | ๋ฌธ์ž B OR์„ ์˜๋ฏธํ•˜๋ฉฐ ๋ฌธ์ž A์™€ ๋ฌธ์ž B๋ฅผ ํฌํ•จํ•˜๋Š” ๋ฌธ์ž๋ฅผ ์กฐํšŒ 

 

๋ฐ˜์‘ํ˜•