MySQL 中的复杂拆分逗号值
Complex split comma value in MySQL
下面是我的问题
我有字符串“1,2,3,4,5”。我想拆分值并放入一个温度 table 但我想插入 1 个位置,我的意思是输出将是
N°1 | N°2
---------
1 | 2
2 | 3
3 | 4
4 | 5
希望有人能解决我的问题。谢谢!
首先,我会要求您完成 this LINK link 以了解在列中存储分隔列表的缺点。
无论如何,如果您使用 MySql 完成此任务,那么您需要使用如下过程和函数来完成此任务:
第 1 步: 创建一个 函数 以 拆分 带分隔符的数据 ,
给定位置。
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, '');
现在,上述函数将仅为给定位置拆分数据。为了拆分整个字符串,我们需要迭代这个函数。这是我们的第 2 步。
步骤 2: 创建 Procedure 以迭代上述函数;
CREATE PROCEDURE ABC(IN fullstr varchar(1000))
BEGIN
DECLARE a INT Default 0;
DECLARE str VARCHAR(255);
DECLARE prev VARCHAR(255);
simple_loop: LOOP
SET a=a+1;
IF a=1 THEN
SET prev=SPLIT_STR(fullstr,",",a);
SET a=a+1;
END IF;
SET str=SPLIT_STR(fullstr,",",a);
IF str='' THEN
LEAVE simple_loop;
END IF;
#Do Inserts into temp table here with str going into the row
insert into t1 values (prev,str);
SET prev=str;
END LOOP simple_loop;
步骤 3: 调用过程:
call abc(columnName);
第 4 步: 从 temp
获取数据 table:
select *
from temp;
希望对您有所帮助!
对于一个简单的 table 就像下面语法创建的
CREATE TABLE `demo2` (
`no1` int(11) NOT NULL,
`no2` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
您可以试试下面的存储过程。
Example of adding +1 to each value in string on each insert
CREATE PROCEDURE `dowhile`(IN `s1` VARCHAR(255))
BEGIN
SET @length = CHAR_LENGTH(`s1`);
SET @counter = 1;
WHILE @counter <= @length DO
SET @char = SUBSTRING(`s1`, @counter, 1);
IF STRCMP(@char, ",") <> 0 THEN
INSERT INTO `demo2` (`no1`,`no2`) VALUES (@char,@char+1);
END IF;
SET @counter = @counter + 1;
END WHILE;
END
Example of adding in field
no1
thenth
element and inno2
thenth+1
arithmetic element in string (not counting comma)
CREATE PROCEDURE `dowhile`(IN `s1` VARCHAR(255))
BEGIN
SET @length = CHAR_LENGTH(`s1`);
SET @counter = 1;
WHILE @counter <= @length DO
SET @next_el_counter = @counter + 2;
SET @char = SUBSTRING(`s1`, @counter, 1);
IF STRCMP(@char, ",") <> 0 THEN
INSERT INTO `demo2` (`no1`,`no2`) VALUES (@char,SUBSTRING(`s1`, @next_el_counter, 1));
END IF;
SET @counter = @counter + 1;
END WHILE;
END
别忘了调用它...
CALL `dowhile`('1,2,3,4,5');