Computer/Databases
[MySQL] Substring 사용
인생이글케쉬우냐
2013. 8. 29. 17:25
개발을 하다보면
가끔 데이터를 내마음대로 성형(?)해서 써야할 때가 있다.
그중 하나가 substring인데,
특정 인덱스나 문자를 기준으로 잘라주는 역할을 한다.
MySql에는 대표적으로 Substring과 Substring_index를 쓰는것 같다.
[방법 1] substring_index 사용시
예) substring_index( 대상문자, 구분자, 인덱스)
select code, substring_index(code, '-', 2), substring_index(code, '-', 3), substring_index( code, '-', -2), substring_index( code, '-', -3) from Product;
인덱스 값을 마이너스로 줬을때는 아래에 있는 substring_index( code, '-', -2)나 substring_index( code, '-', -3)의 결과 처럼 꺼꾸로 시작하는 인덱스가 된다.
[방법 2] substring 사용시
예) substring( 대상문자, 시작인덱스, 읽어들일 길이)
select code, substring(code, 8, 3), substring(code, 12, 1) from Product;
아래 그림과 같이 결과가 나온다.
substring(code, 8, 3)과 같은 결과를 자바에서 찾을때는 아래와 같이 인덱스 값이 좀 다르다.
code.substring( 7, 10);
[참고]
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring
반응형