📝MySQL Workbench 문자열 컬럼의 데이터를 가공하는 함수들
문자열을 합치는 concat()
+ 여러 문자열 컬럼을 합칠때 그 사이를 첫번째 입력한 파라미터로 합치는 concat_ws()
문자열의 일부분만 가져오는 substring()
문자열의 내용을 바꾸는 replace()
문자열의 순서를 역순으로 바꿔주는 reverse()
문자열의 갯수(길이)를 구하는 char_length()
문자열의 대소문자 처리하는 upper(), lower()
문자열을 합치는 함수 concat()
※ 공백이나 다른 문자열을 포함시킬 수 있다
-- author_fname 과 author_lname 컬러의 값을 합해서 full_name 이라고 보여주기
select concat(author_fname, ' ', author_lname) as full_name
from books;
여러 문자열 컬럼을 합칠때 그 사이를 첫번째 입력한 파라미터로 합치는 concat_ws()
-- author_fname 과 author_lname 컬러의 값을 합해서 full_name 이라고 보여주기
select concat_ws(' ', author_fname, author_lname) as full_name
from books;
문자열의 일부분만 가져오는 함수 substring()
※ substr과 동일 / 서브스트링 함수의 시작위치는 1부터 시작한다
-- 책 제목을 첫글자부터 10번째까지만 가져오기
select substring(title, 1, 10) as title
from books;
-- 타이틀 컬럼의 내용을 맨 위에서 5번째 글자부터 끝까지 가져오기
select substring(title, -5) as title_end
from books;
-- 타이틀을 가져오되 5번째 글자부터 15번째 글자까지 가져오기
select substring(title, 5, 15) as title_end
from books;
문자열의 내용을 바꾸는 replace()
-- 책 제목에 The 가 있으면 Hello로 변경하고 싶다
select replace(title, 'The', 'Hello')
from books;
-- 책 제목에 The 가 있으면 제거하고 싶다
select replace(title, 'The', '')
from books;
문자열의 순서를 역순으로 바꿔주는 reverse()
-- authoer_lname을 역순으로 가져오기
select reverse(author_lname)
문자열의 갯수(길이)를 구하는 char_length()
-- 책 제목의 길이를 구하기
select char_length(title) as title_cnt
from books;
문자열의 대소문자 처리하는 upper(), lower()
-- 작가 이름 author_fname을 대문자로 바꾸기
select upper(author_fname) as upper_fname
from books;
-- 작가 이름 author_fname을 소문자로 바꾸기
select lower(author_fname) as lower_fname
from books;
이 함수들을 조합하여 사용한다
-- 책 제목을 맨 앞부터 10글자만 가져오고 뒤에 ...을 붙인다
-- 예) The Namesa...
select concat( substring(title, 1, 10), '...') as title
from books;
-- 타이틀의 공백을 ->으로 바꿔 나오도록 가져온다
select replace(title, ' ', '->') as title
from books;
-- author_lname 컬럼과 순서를 바꾼 author_lname 컬럼이 나오도록 가져온다
select author_lname as forwards, reverse(author_lname) as backwards
from books;
-- author_fname과 author_lname을 합치되 대문자로 나오게 가져온다
select upper(concat(author_fname, ' ', author_lname)) as 'full name in caps'
from books;
-- 타이틀컬럼과 년도컬럼을 합치되 중간에 was released in이 들어가게 가져온다
select concat_ws('was released in ', title, released_year) as blurb
from books;
-- 타이틀과 타이틀에 적힌 글자의 갯수가 나오게 가져온다
select title, char_length(title) as character_count
from books;
-- 타이틀을 맨 앞부터 10글자만 가져와 뒤에 ...을 붙이고
-- author_fname과 author_lname을 합치고
-- stock_quantity에는 in stock이 붙도록 가져온다
select concat( substring(title, 1, 10), '...') as short_title,
concat(author_fname, ',', author_lname) as author,
concat(stock_quantity,'in stock') as quantity
FROM books;
'MySQL' 카테고리의 다른 글
[MySQL] 데이터 집계함수 count, sum, avg, max, min (0) | 2022.12.07 |
---|---|
[MySQL] 데이터를 가공하는 키워드 distinct, order by, limit, like (0) | 2022.12.07 |
[MySQL] 테이블 데이터 CRUD(Create, Read, Update, Delete) (0) | 2022.12.06 |
[MySQL] id 컬럼 만들기 (0) | 2022.12.06 |
[MySQL] Null, Not Null 과 Default의 동작 방식 (0) | 2022.12.06 |
댓글