SQL

[MySQL] 비교문과 조건문: between, in, case, if, ifnull

eyoo 2022. 5. 16. 17:09

where를 사용하여 년도가 2017인 데이터 가져오자

 

in:

select * 
from books
where released_year = 2017;

out:

 

 

이번에는 2017년이 아닌 데이터만 가져오자

 

in:

select * 
from books
where released_year != 2017
order by released_year desc;

out:

# '!=' 사용하면 쉽게 가져올수 있다.

 

 

author_lname 이 Harris 가 아닌 데이터만 가져오자


in:

select * 
from books
where author_lname != 'Harris';

out:

# 문자열 데이터도 '!=' 를 사용하여 가져올수 있다.

 

 

책 제목이 w 로 시작하는 책을 가져오자


in:

select * 
from books
where title like 'w%';

out:

# like를 사용하여 가져왔다.

 

 

책 제목이 'w' 로 시작하지 않는 책을 가져오자.

in:

select * 
from books
where title not like 'w%';

out:

# like를 사용할때는 '!=' 를 활용하지않고 like앞에 not을 붙여준다.

 

 

년도가 2000년 보다 큰 데이터를 가져오자


in:

select * 
from books
where released_year > 2000;

out:

# 부등호를 활용하여 가져왔다.

 

 

author_lname 이 'Eggers'이고, 년도는 2000년 이후인 데이터를 가져오자

 

in:

select *
from books
where author_lname = 'Eggers' and released_year > 2000;

out:

# 두 조건을 모두 만족하는 데이터를 가져오기 위해 and를 사용했다.

 

 

author_lname 이 'Eggers'이고, 년도는 2000년 이후이며 제목에 novel이 들어간 데이터를 가져오자

 

in:

select *
from books
where author_lname = 'Eggers' and released_year > 2000 and title like '%novel%';

out:

 

 

author_lname이 Eggers이거나 출간년도가 2010보다 큰 책을 가져오자

 

in:

select *
from books
where author_lname = 'Eggers' or released_year > 2010;

out:

# 두 조건중 하나 이상을 만족하는 데이터를 가져오기 위해 or를 사용했다.

 

 

무엇과 무엇 사이의 데이터를 가져올떄

년도가 2004년부터 2015년까지의 (사이의) 책 데이터를 가져오자

 

in:

select *
from books
where released_year >= 2004 and released_year <= 2015 ;

out:

 

 

이것을 between을 사용하여 나타낼수도 있다.

 

in:

select *
from books
where released_year between 2004 and 2015;

out:

 

 

author name이 'carver' 이거나 'Lahiri' 이거나, 'Smith'인 데이터만 가져오자

 

in:

select *
from books
where author_lname = 'Carver' or author_lname = 'Lahiri' or author_lname = 'Smith' ;

out:

# or를 두번이나 더 써서 나타내었다.

 

 

이것을 in을 사용하여 나타낼수도 있다.

 

in:

select *
from books
where author_lname in('Carver','Lahiri','Smith');

out:

 

 

Case 문을 사용해서 데이터를 분류하여 이름 붙여줄수 있다.

년도가 2000년 이후의 것은 modern이라고 하고 그렇지 않은것은 old 라 하는 새로운 컬럼을 만들자.

in:

select * , 
	case 
		when released_year >= 2000 then 'Modern'
        	else 'Old'
	end as Genre
from books

out:

# case는 조건문인 when과 then을 사용하며 end로 끝난다.

# end 뒤에 as를 붙여 컬럼명을 정할수있다.

 

 

 

case로 아래의 조건을 만족시키는 코드를 만들자.

stock_quantity 가 0~50 사이면 , * (별표한개), stock_quantity 가 51~100 사이면  ** (별표두개), 그 외는 *** (별표한개)

in:

select * , 
	case 
		when stock_quantity between 0 and 50 then '*'
		when stock_quantity between 51 and 100 then '**'
		else '***'
	end as star
from books;

out:

 

 

if 함수를 사용할수 있다.
pages가 300보다 크면 long 아니면 short로 정하자.

 

in:

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

out:

# 첫번째 파라미터에 조건을

# 두번째 파라미터에 True일때 반환되는값

# 세번째 파라미터에 False일때 반환되는값을 입력한다.

 

 

ifnull함수를 사용하여 null 값을 다른값으로 변경할수 있다.

 

in:

select *,
ifnull(age,100)
from people;

out:

# 첫번째 파라미터에 해당 컬럼을

# 두번째 파라미터에 null일때 반환되는값을 입력한다.