본문 바로가기

TOOL/MySQL

MySQL - if( )

반응형
if

 

 

 

 

if( ) 함수

 

 

2가지 경우에대한 조건문 작성이 가능한 함수이다.

 

 

if ( 조건, 조건이라면, 조건이 아니라면 )

 

순서대로 작성해야한다.

 

select *
from books;

 

 

pages가 300보다 크면 long이라고 하고, 그렇지않으면 short라고 한다.

 

select *, if(pages >= 300, 'long', 'short' )
from books;

 

 

select title, author_lname, if(count(*) = 1, concat(count(*),' book'), concat(count(*),' books')) as COUNT
from books
group by author_fname, author_lname
order by author_lname;

 

 

select레벨에서는 없던 컬럼을 이름을 지어서 사용하면 에러가 난다. 그러므로 if다음 average가 들어갈 수 없다.

 

select first_name, avg( ifnull(grade, 0)) as average, if(avg(grade) >= 80, 'PASSING', 'FAILING') as passing_status
from students s
left join papers p
on s.id = p.student_id
group by s.id
order by average desc;

반응형