本文介绍了Mysql字符串拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列和一个逗号分隔的列如下



例如,
我有表,

  Col1 | col2 
1 | a,b,c
2 | d,e



从上面,我想要

  Col1,Col2 
1,a
1,b
1,c
2,d
2,e

如何实现



解决方案

您可以使用存储过程来完成此操作



DELIMITER $$

CREATE FUNCTION strSplit(x VARCHAR(65000),delim VARCHAR(12),pos INTEGER)
RETURNS VARCHAR(65000)
BEGIN
DECLARE输出VARCHAR(65000);
SET output = REPLACE(SUBSTRING(SUBSTRING_INDEX(x,delim,pos)
,LENGTH(SUBSTRING_INDEX(x,delim,pos_1))+ 1)
,delim
,'');
IF output =''THEN SET output = null;万一;
RETURN output;
END $$


CREATE PROCEDURE BadTableToGoodTable()
BEGIN
DECLARE i INTEGER;

SET i = 1;
REPEAT
INSERT INTO GoodTable(col1,col2)
SELECT col1,strSplit(col2,',',i)FROM BadTable
WHERE strSplit(col2,',',i )IS NOT NULL;
SET i = i + 1;
UNTIL ROW_COUNT()= 0
END REPEAT;
END $$

DELIMITER;


I have one string column and one comma separated column as below

Example,I have the table,

Col1 | col2
1    | a,b,c
2    | d,e

From above, I want

Col1,Col2
1   ,a
1   ,b
1   ,c
2   ,d
2   ,e

How to achieve this

It is not the Exact Duplicate.

解决方案

You can do this using a stored procedure

DELIMITER $$

CREATE FUNCTION strSplit(x VARCHAR(65000), delim VARCHAR(12), pos INTEGER)
RETURNS VARCHAR(65000)
BEGIN
  DECLARE output VARCHAR(65000);
  SET output = REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos)
                 , LENGTH(SUBSTRING_INDEX(x, delim, pos - 1)) + 1)
                 , delim
                 , '');
  IF output = '' THEN SET output = null; END IF;
  RETURN output;
END $$


CREATE PROCEDURE BadTableToGoodTable()
BEGIN
  DECLARE i INTEGER;

  SET i = 1;
  REPEAT
    INSERT INTO GoodTable (col1, col2)
      SELECT col1, strSplit(col2, ',', i) FROM BadTable
      WHERE strSplit(col2, ',', i) IS NOT NULL;
    SET i = i + 1;
    UNTIL ROW_COUNT() = 0
  END REPEAT;
END $$

DELIMITER ;

这篇关于Mysql字符串拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 09:24