DATABASE/MySQL Workbench

MySQL Workbench : 문자열 검색에 유용한 like 사용법

신강희 2024. 5. 14. 17:19
728x90

< MySQL 문자열 검색에 유용한 like 사용법 >

# 이전 생성한 스키마(DB)와 테이블로 이어서 진행

# 참고 : https://sorktjrrb.tistory.com/105

 

MySQL Workbench : 문자열 처리 함수들 (concat, concat_ws, substring)

# 문자열 처리 함수 학습을 위해 books 라는 새로운 테이블 생성ㄴ 혹시 테이블을 수정하고 싶으면 좌측 목록에서 체크된 아이콘을 누르면 수정 가능! # yhdb 를 사용하였으므로, 해당 db 사용 문구

sorktjrrb.tistory.com

 

# 문자열 검색 키워드 like

# 같은걸 찾는것이 아니라 포함되어 있는걸 찾는것!

-- 문자열안에 원하는 문자가 들어있는지 검색한느 키워드 like

-- 책 제목에 the 가 들어있는 데이터를 가져오시오.
-- 책 제목이 the 인거 가져오시오. 와는 완전히 다른것!!

-- 이건 같은걸 찾는것!
select *
from books
where title = 'the';

-- 들어있는 데이터를 찾을땐 like '%문자열%';
-- %의미는 위치가 상관없다는 뜻, 즉 앞이 뭐로 시작되든 끝이 뭐든 중간에 the가 들어있기만 하면 가져와라.
select *
from books
where title like '%the%';

 

# '%' 위치에 따라 문자열 위치 조정

-- 책 제목에, 시작이 the 로 시작하는 데이터를 가져오시오.
-- 즉, 앞에 % 빼면 시작은 무조건 the고 그뒤는 상관없다는 뜻.
select *
from books
where title like 'the%';

-- 책 제목에, 끝이 the 로 끝나는 데이터를 가져오시오.
select *
from books
where title like '%the';

ㄴ title 이 'the'로 시작하는 데이터

 

# 자릿수로 불러올때는 '_' 언더스코어 사용

-- stock_quantity 의 숫자가, 두자리인 데이터만 가져오시오.
-- 언더스코어 사용! _ 언더스코어 두개 사용하면 두자리수만 가져옴.
select *
from books
where stock_quantity like '__';

 

# 조건문과 like를 같이 사용도 가능

-- pages 수는 100 보다 크고, 책 제목에 the 가 들어간 책을 가져오되
-- 재고수량 내림차순으로 데이터를 3개만 가져오시오.
select *
from books
where pages > 100 and title like '%the%'
order by stock_quantity desc
limit 0, 3;

 

# 포함되지 않는 데이터를 찾을때는 not like

-- 책 제목에, talk 가 들어가지 않은 데이터만 가져오시오.
select *
from books
where title not like '%talk%';

 

# 실습문을 통해 정리해 보자.

-- 실습
-- 1) 제목에 stories 가 포함된 데이터를 제목만 조회
select title
from books
where title like '%stories%';

 

-- 2) 페이지수가 가장 긴 책을 찾고, 제목과 페이지수 확인
select title, pages
from books
order by pages desc
limit 1;

 

-- 3) 가장 최근 발간된 책 3권, 책 제목과 발간년도 조회
-- 다음처럼 하이픈(-) 을 붙여서 조회 (컬럼명은 summary)
select concat(title, ' - ', released_year) as summary
from books
order by released_year desc
limit 3;

 

-- 4) author_lname 에 공백("") 이 들어있는 사람의 책 제목과 author_lname을 조회
select title, author_lname
from books
where author_lname like '% %';

 

-- 5) stock_quantity가 적은 책 3권의
-- title, year, stock_quantity를 조회
select title, released_year, stock_quantity
from books
order by stock_quantity asc
limit 3;

 

-- 6) author_lname 과 title 로 정렬한후,
-- title과 author_lname을 조회하시오.
select title, author_lname
from books
order by author_lname, title;

 

-- 7) author_lname 으로 정렬하되,
-- 'My favorite author is' 를 붙여서 조회하시오.
select upper( concat('MY FAVORITE AUTHOR IS ' , author_fname, ' ' , author_lname, '!')) as yell
from books
order by author_lname;

 

다음 게시글로 계속!

반응형