구분 기호를 사용한 MySQL 부분 문자열 추출
MySQL의 문자열에서 서브스트링을 추출하고 싶습니다.문자열에는 쉼표('',')로 구분된 여러 개의 하위 문자열이 들어 있습니다.저는 어떤 MySQL 함수를 사용해서 이 서브스트링들을 추출해야 합니다.
예를 들어,
Table Name: Product
-----------------------------------
item_code name colors
-----------------------------------
102 ball red,yellow,green
104 balloon yellow,orange,red
색상 필드를 선택하고 기판을 빨간색, 노란색, 녹색으로 쉼표로 구분하여 추출하고 싶습니다.
안타깝게도 MySQL에는 분할 문자열 기능이 없습니다.위 링크와 같이 사용자 정의 분할 기능이 있음을 나타냅니다.
데이터를 가져올 수 있는 좀 더 자세한 버전은 다음과 같습니다.
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(colors, ',', 1), ',', -1) as colorfirst,
SUBSTRING_INDEX(SUBSTRING_INDEX(colors, ',', 2), ',', -1) as colorsecond
....
SUBSTRING_INDEX(SUBSTRING_INDEX(colors, ',', n), ',', -1) as colornth
FROM product;
https://blog.fedecarg.com/2009/02/22/mysql-split-string-function/, 을 기반으로 구분 기호로 구분된 배열에서 값에 액세스하는 방법은 다음과 같습니다.
/*
usage:
SELECT get_from_delimiter_split_string('1,5,3,7,4', ',', 1); -- returns '5'
SELECT get_from_delimiter_split_string('1,5,3,7,4', ',', 10); -- returns ''
*/
CREATE FUNCTION get_from_delimiter_split_string(
in_array varchar(255),
in_delimiter char(1),
in_index int
)
RETURNS varchar(255) CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci
RETURN REPLACE( -- remove the delimiters after doing the following:
SUBSTRING( -- pick the string
SUBSTRING_INDEX(in_array, in_delimiter, in_index + 1), -- from the string up to index+1 counts of the delimiter
LENGTH(
SUBSTRING_INDEX(in_array, in_delimiter, in_index) -- keeping only everything after index counts of the delimiter
) + 1
),
in_delimiter,
''
);
참조용 문자열 연산자 문서: https://dev.mysql.com/doc/refman/8.0/en/string-functions.html
64~69번 라인에서 SPRIT_STR 기능 사용을 확인합니다.
언급URL : https://stackoverflow.com/questions/34992575/mysql-substring-extraction-using-delimiter
'programing' 카테고리의 다른 글
| WordPress get_posts를 제목별로 예를 들어 다음과 같이 입력합니다. (0) | 2023.10.11 |
|---|---|
| 다른 파이프라인 함수를 호출하는 파이프라인 함수 (0) | 2023.10.11 |
| Mysql 색상 체계 (0) | 2023.10.11 |
| 관련이 없는 SELECT 문으로 다른 결과를 반환하는 동시 MYSQL 프로시저 호출 (0) | 2023.10.11 |
| SQL 상태 [9999]; 오류 코드 [17004];잘못된 열 유형: 1111 With Spring SimpleJdbcC 호출 (0) | 2023.10.11 |