2012-04-03 38 views
1

MySQL中有任何函數用於爆炸某列的數據然後檢索它嗎? 如果列數據是P:12,那麼數據可以在':'上分解,然後讀取?類似於MySQL中爆炸工作的函數

+0

不回答您的問與答,但你應該總是儘量保持只有一個數據塊中的任何一個字段/記錄。在這種情況下,如何將P從12分開存儲? – Basic 2012-04-03 08:23:40

+0

看起來這個問題曾被問到過:http://stackoverflow.com/questions/471914/can-you-split-explode-a-field-in-a-mysql-query – Bram 2012-04-03 08:21:03

回答

1

你可以寫在MYSQL分流功能檢查這個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, ''); 

用法

SELECT SPLIT_STR(string, delimiter, position) 

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

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

我解析使用while循環的串和插入拆分項到臨時表。這很複雜,但我複製並粘貼代碼,然後更改表名以提高可讀性。下面是一個例子來分析用戶ID的逗號分隔列表到一個臨時表:

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