MySQL - 문자열 함수 (concat/concat_ws, substring, replace, reverse, char_length, upper/lower)

반응형

  • 'books' 테이블


concat/concat_ws

  • concat : 데이터 합치기 (하나의 컬럼으로 표현)
    • 작가 성과 이름(author_fname, author_lname) 합치기 
      • select concat(author_fname, author_lname) from books;
      • select concat(author_fname, author_lname) as full_name from books;
        • 열의 이름을 변경하여 더욱 보기 좋게 할 수 있음 -> as 바꿀이름

 

  • concat_ws : 처음의 구분자를 정해주면 구분자를 넣어 합쳐줌
    • 작가 성과 이름(author_fname, author_lname) 사이에 공백 줘서 합치기
      • select concat_ws(' ',author_fname, author_lname) as full_name from books;


substring

  • substring : 특정 문자열의 위치만 출력 (슬라이싱과 같은 개념)
  • substring(데이터, 시작위치, 끝위치)
    • 책 제목(title)을 처음부터 10글자까지만 가져오기
      • select substring(title, 1, 10) from books;

 

  • 응용) 책 이름(title 컬럼)의 10글자씩 출력하고 뒤에 '...'을 붙여보고 title로 이름 짓기
    • select concat(substring(title, 1, 10), '...') as title from books;


replace

  • replace : 특정 문자열 변경
  • replace(변경 할 값, 변경 될 문자, 변경 할 문자)
    • 책 제목(title)의 e를 3으로 바꿔보기
      • select replace( title ,'e', 3) from books;


reverse

  • reverse : 문자열의 순서를 반대로 변경
    • 작가의 성(author_fname)을 을 뒤집어서 가져오기
      • select reverse(author_fname) from books;


char_length

  • char_length : 문자열의 길이 값 반환
    • 책 제목(title)의 길이 구하기
      • select char_length(title) from books;


upper/lower

  • upper/lower : 영문자를 대문자(upper), 소문자(lower)로 변환
    • 책 제목(title)을 대문자와 소문자로 변경해보기
      • select upper(title) from books;
      • select lower(title) from books;

 

반응형