Function resembling the work of Explode in MySQL

岁酱吖の 提交于 2019-12-02 11:35:54

问题


Is there any function in MySQL to explode data of a column and then retrieve it? Like if a column data is P:12 , then can the data be exploded on ':' and then read?


回答1:


Here are many discussion about the SPLIT problem in mysql :

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html




回答2:


You can write a Split function in MYSQL check this link

From the Link

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)

RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');

Usage

SELECT SPLIT_STR(string, delimiter, position)

Example

SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;

+-------+
| third |
+-------+
| ccc   |
+-------+



回答3:


I parse the string using a while loop and insert the split items into a temporary table. It's complicated, but I copy and paste the code, then change the table name for readability. Here's an example to parse a comma delimited list of user ids into a temp table:

CREATE PROCEDURE spParse
(_UserList MEDIUMTEXT)
BEGIN
    DECLARE _Pos INT;
    DECLARE _Start INT;
    DECLARE _Item INT;
    DECLARE _Length INT;

    CREATE TEMPORARY TABLE IF NOT EXISTS TempUserList
    (
        UserID INT
    );

    SET _Length = LENGTH(_UserList);
    SET _Pos = 1;
    SET _Start = 1;
    divide_loop:LOOP
        IF _Pos > _Length Then
            LEAVE divide_loop;
        End If;
        IF SUBSTRING(_UserList,_Pos,1) = ',' Then
            IF _Pos - _Start > 0 Then
                IF IsNumeric(SUBSTRING(_UserList,_Start,_Pos-_Start)) Then
                    SET _Item = CONVERT(SUBSTRING(_UserList,_Start,_Pos-_Start),Signed);
                    INSERT INTO TempUserList (UserID)
                    VALUES (_Item);
                End If;                 
            End If;
            SET _Start = _Pos + 1;
        End If;
        SET _Pos = _Pos + 1;
    END LOOP divide_loop;
    IF _Start <= _Length Then
        If IsNumeric(SUBSTRING(_UserList,_Start,_Length - _Start + 1)) Then
            SET _Item = CONVERT(SUBSTRING(_UserList,_Start,_Length - _Start + 1),Signed);       
            INSERT INTO TempUserList (UserID)
            VALUES (_Item);
        End If;
    End If;

    SELECT UserID FROM TempUserList;

    DROP TABLE TempUserList;
END


来源:https://stackoverflow.com/questions/9989546/function-resembling-the-work-of-explode-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!