T_era

[MySQL] 조건문 사용하기 본문

Programing/Datababse

[MySQL] 조건문 사용하기

블스뜸 2025. 3. 21. 15:14

IF : 컬럼에 조건을 넣어 출력
ex) SELECT name, IF(nation = 'Korean', '한국인', '외국인') FROM human // nation이 korean이면 한국인 아니면 외국인으로 출력

CASE WHEN THEN ELSE END : case로 조건문 시작 when으로 조건 작성 then으로 부합하는 경우 작성 else 조건이 모두 안맞을 경우 작성 end로 case 종료
ex) 30대 20대 10대로 분류하기
select case when age >= 30 then '30대'
when age >= 20 then '20대'
when age >= 10 then '10대'
else '기타' end
or
select case when age between 10 and 19 then "10대" // 해당하는 연산자도 가능

IN : 포함하기
ex)한국인과 아시아인으로 나누기
case when nation = 'korean' then '한국인'
 when nation in ('japanese', 'chinese') then '아시아인' end
from human

as decimal : 숫자로 형변환
as char : 문자로 형변환