AWS/MySQL

MySQL 문자열 컬럼의 데이터를 가공하는, 여러함수들

leopard4 2022. 12. 6. 17:30

테스트용 테이블

-- 연습용 테이블 생성을 위한 코드
INSERT INTO books (title, author_fname, author_lname, released_year, stock_quantity, pages)
VALUES
('The Namesake', 'Jhumpa', 'Lahiri', 2003, 32, 291),
('Norse Mythology', 'Neil', 'Gaiman',2016, 43, 304),
('American Gods', 'Neil', 'Gaiman', 2001, 12, 465),
('Interpreter of Maladies', 'Jhumpa', 'Lahiri', 1996, 97, 198),
('A Hologram for the King: A Novel', 'Dave', 'Eggers', 2012, 154, 352),
('The Circle', 'Dave', 'Eggers', 2013, 26, 504),
('The Amazing Adventures of Kavalier & Clay', 'Michael', 'Chabon', 2000, 68, 634),
('Just Kids', 'Patti', 'Smith', 2010, 55, 304),
('A Heartbreaking Work of Staggering Genius', 'Dave', 'Eggers', 2001, 104, 437),
('Coraline', 'Neil', 'Gaiman', 2003, 100, 208),
('What We Talk About When We Talk About Love: Stories', 'Raymond', 'Carver', 1981, 23, 176),
("Where I'm Calling From: Selected Stories", 'Raymond', 'Carver', 1989, 12, 526),
('White Noise', 'Don', 'DeLillo', 1985, 49, 320),
('Cannery Row', 'John', 'Steinbeck', 1945, 95, 181),
('Oblivion: Stories', 'David', 'Foster Wallace', 2004, 172, 329),
('Consider the Lobster', 'David', 'Foster Wallace', 2005, 92, 343);
SELECT * 
FROM books;

-- 문자열을 합치는 함수 concat()
-- author_fname 과 author_lname  컬럼의 값을 합해서 
-- 보여주고 싶다.
-- full_name 이라고 보여주고 싶다.
select concat(author_fname,' ', author_lname) as full_name
from books;

-- concat_ws() 함수를 이용하는 방법
select concat_ws(' ' ,author_fname, author_lname) as full_name
from books; 




-- 문자열의 일부분만 가져오는 함수 substring()
-- 책 제목을 첫글자부터 10번째까지만 가져오기
-- 서브스트링 함수의 시작위치는 1부터!!!
select substring(title, 1, 10) as title
from books;


-- 타이틀 컬럼의 내용을, 맨 뒤에서 5번째 글자부터 끝까지 가져오시오.
select substring(title,-5) as title_end
from books;

-- 타이틀을 가져오되, 5번째 글자부터 15번째 글자까지 가져오시오.
-- substr() == substring()
select substr(title, 5, 15) as title_515 
from books;

-- 문자열의 내용을 바꾸는, replace() 함수
-- 책 제목에 The 가 있으면, 제거하고 싶다.

select replace(title, 'The', 'Hello') 
from books;

-- 문자열의 순서를 역순으로 바꿔주는 reverse
-- 작가 author_lname 을 역순으로 가져오시오.

select reverse(author_lname)
from books;

-- 책 제목을 맨 앞부터 10글자만 가져오고, 뒤에 ...을 붙인다.
-- 예) The Namesa...
-- 예2) Norse Myth...
select concat(substr(title,1, 10) , "...") as title
from books;

-- 문자열의 개수(길이) 를 구 하는 함수 char_length()
-- 책 제목의 길이를 구하시오.
select char_length(title) as title_cnt
from books;


-- 대소문자 처리하는 함수 upper() lower()
-- 작가 이름 author_fname을 대문자로 바꾸시오.
select upper(author_fname) as upper_fname
from books;