programing

구분 기호를 사용한 MySQL 부분 문자열 추출

javajsp 2023. 10. 11. 20:29

구분 기호를 사용한 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