[MySQL] 문자열 편집: concat, concat_ws, substr, replace, reverse, char_length, upper,
books 테이블을 만들었다.
concat 함수를 사용하여 작가이름을 합쳐서 full name으로 가져오자.
in:
select concat(author_fname,' ', author_lname) as full_name
from books;
out:
# as를 사용하여 보여지는 컬럼명을 설정할수 있다.
concat_ws 로 두개 이상의 데이터들 사이를 원하는 문자로 설정하여 연결시킬수있다.
in:
select concat_ws(' ',author_fname, author_lname,released_year) as full_name
from books;
out:
# 첫번쨰 파라미터로 어떤 문자를 넣을지 설정하면 된다.
substr함수를 이용해서 문자열의 일부분만 가져오자 (파이썬의 슬라이싱과 비슷하다.)
제목을 처음부터 10글자까지만 가져오기
in:
select substr(title,1,10) as title
from books;
out:
# 첫번째 파라미터에 해당 컬럼을
# 두번째 파라미터에 시작점(0이 아닌 1부터 시작하며 포함된다.)
# 세번째 파라미터에 끝점을 넣는다. (역시 포함된다.)
제목의 맨 뒤에서 5번째 글자부터 끝까지 가져오자
in:
select substr(title,-5) as title
from books;
out:
# 마지막에서 5번째로 -5를 입력한다.
# 끝까지 가져오고 싶다면 마지막 파라미터는 생략한다.
제목의 처음부터 10글자를 가져오되 뒤에 ...을 붙여서 가져오자
in:
select concat(substr(title,1,10),'...') as short_title
from books;
out:
# 함수들을 조합하여 나타낼수 있다.
# substr 함수와 '...'을 concat 함수로 감싸준다는 느낌으로 입력했다.
replace 함수를 사용하여 원하는 문자를 바꿔줄수있다.
title 컬럼에 들어있는 e를 3으로 바꿔서 가져와라
in:
select replace(title,'e','3')
from books;
out:
# 첫번째 파라미터에 해당 컬럼을
# 두번째 파라미터에 변경할 문자,
# 세번째 파라미터에 대신할 문자를 넣는다.
reverse 함수로 문자열의 순서를 거꾸로 뒤집을수 있다
author_fname을 뒤집어서 가져오자
in:
select reverse(author_fname)
from books;
out:
char_length 함수로 문자열의 길이를 구할수 있다.
in:
select char_length(title) as length
from books;
out:
upper와 lower로 대소문자를 바꿀수 있다.
in:
select upper(title)
from books;
select lower(title)
from books;
out:
[실습]
책 제목 길이는 ~ 으로 시작하는 문자열로 책 제목 길이를 나타내자
in:
select concat_ws(' ','책 제목의 길이는',char_length(title))
from books;
out:
제목 사이를 -> 로 바꾸자
in:
select replace(title,' ','->') as title
from books;
out:
작가의 풀네임을 대문자로 나타내자.
in:
select upper(concat_ws(' ',author_fname,author_lname)) as full_name_in_caps
from books;
out: