DATABASE/MySQL Workbench

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

신강희 2024. 5. 14. 15:12
728x90

< MySQL 문자열 처리 함수들 concat(), concat_ws(), substring() >

# 문자열 처리 함수 학습을 위해 books 라는 새로운 테이블 생성

ㄴ 혹시 테이블을 수정하고 싶으면 좌측 목록에서 체크된 아이콘을 누르면 수정 가능!

 

# yhdb 를 사용하였으므로, 해당 db 사용 문구 및 데이터 삽입!

use yhdb;

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);

 

# 문자를 합치는 함수 concat(), concat_ws()

-- 문자열을 합치는 함수 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 ) full_name
from books;

ㄴ 결과는 두 명령어 모두 동일함

 

-- 이름 두개를 붙여서, full_name 을 만들고,
-- 책 제목과 출간년도를 같이 보여달라.
select concat(author_fname, ' ' ,author_lname) full_name, 
	title, 
    released_year
from books;

 

# 일부부만 가져와 보이기 substring()

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

 

-- 다른 컬럼을 붙이고 싶다.
select substring( title, 1, 10 ) title, pages, released_year
from books;

 

-- 제목을, 맨 뒤에서 5번째 글자부터 끝까지 다 나오도록 데이터를 가져오시오.
select substring( title, -5 ) title
from books;

 

-- 제목을, 앞에서 3번째 글자부터 끝까지 다 나오도록 데이터를 가져오시오.
select substring(title, 3) title
from books;

 

다음 게시글로 계속!

반응형