DB/명령프롬프트 - mysql

[MySQL] SQL 내장함수 : 논리함수 ( if , case ~ when ~then )

congs 2023. 3. 28. 16:59

if 문

if문 :  if(조건식, 참, 거짓);
다중 if문  :  if(조건식, true, if(조건식, true, false));

 

  • 예시 ) at_repetition에 ( at_score =F 이거나 at_attend<=3인 경우 )에는 y, 나머지에는 n을 넣으세요
mysql> update attend set at_repetition =
    -> if(at_score = 'F' or at_attend <=3, 'y', 'n')
    -> where at_term = 1;
  • 예시) at_score가 'A' 또는 'B'일 경우 'p'아니면 'f'를 넣으세요
mysql> update attend set at_pass =
    -> if(at_score = 'A' or at_score = 'B', 'p' , 'f' );

 

case ~ when ~then 문

case
when 조건1 then 값1
when 조건2 then 값2
else 값3
end ;
  • 예시) 점수에 따라 등급 나누기
mysql> update attend set at_score  = (
    -> case
    -> when (at_mid+at_final+at_attend+at_hw) >= 90 then 'A'
    -> when (at_mid+at_final+at_attend+at_hw) >= 80 then 'B'
    -> when (at_mid+at_final+at_attend+at_hw) >= 70 then 'C'
    -> when (at_mid+at_final+at_attend+at_hw) >= 60 then 'D'
    -> else 'F'
    -> end)
    -> where at_term = 1;

 

✔ 변수에도 사용이 가능!

: mySQL에서도 변수 사용 가능

  • set @변수명 = 값;
  • ex) set @score= 78;

mysql> select case

when @score >= 80 then "상" 

when @score >= 60 then "중"

else "하"

end;

'DB > 명령프롬프트 - mysql' 카테고리의 다른 글

[MySQL] SQL 내장함수 : 정보함수  (0) 2023.03.28
[MySQL] ERD 생성  (0) 2023.03.28
[MySQL] join 사용  (0) 2023.03.28
[MySQL] SQL 내장함수 : 문자열 함수  (0) 2023.03.28
[MySQL] SQL 내장함수 : 날짜함수  (0) 2023.03.27