您将获得一个包含两种类型分隔符的字符串。提供了表的模式。如何以有效的方式将分隔的字符串转换为临时表?例如,
Andy~22~US|Jane~24~Australia|Davis~30~UK|Nancy~32~Germany
我是MySql的新手。那么任何帮助将不胜感激?
答案 0 :(得分:0)
我会像这样写它可能有足够的方式使用Name,但它必须工作!
Create table MIX (
`id` int not null,
`x` text not null)
ENGINE = InnoDB;
insert into mix value (1,'Andy~22~US|Jane~24~Australia|Davis~30~UK|Nancy~32~Germany');
create table unmix select
numbers.n as id,
SUBSTRING_INDEX(SUBSTRING_INDEX(x, '~', 2*numbers.n),'~', -1) as Age,
SUBSTRING_INDEX(SUBSTRING_INDEX(x, '|', 1*numbers.n),'~', -1) as Country,
substring_index(SUBSTRING_INDEX(SUBSTRING_INDEX(x,'~', 2*numbers.n),'|',-1),'~',+1) as Name
from
(select 1 n union all
select 2 union all
select 3 union all select 4 )
numbers INNER JOIN mix
on CHAR_LENGTH(mix.x)
-CHAR_LENGTH(REPLACE(mix.x, ' ', ''))>=numbers.n-4;
答案 1 :(得分:0)
谢天谢地,我为自己写了一个简单的代码:
DROP procedure IF EXISTS `split_procedure`;
DELIMITER $$
CREATE DEFINER=`cwuser`@`%%` PROCEDURE `split_procedure`(v_stringtosplit text, v_rowdelim CHAR(5), v_coldelim CHAR(5))
BEGIN
SET @replacetosplit := REPLACE(v_stringtosplit, v_rowdelim, '"),("');
SET @replacetosplit := REPLACE(@replacetosplit, v_coldelim, '","');
SET v_stringtosplit = CONCAT(v_rowdelim, v_stringtosplit);
SET @no_of_rows = length(v_stringtosplit) - length(replace(v_stringtosplit, v_rowdelim, ''));
SET @rownum = 1;
SET @no_of_cols = length(v_stringtosplit) - length(replace(v_stringtosplit, v_coldelim, ''));
SET @no_of_cols = (@no_of_cols / @no_of_rows);
SET @colnum = 1;
DROP TABLE IF EXISTS temporary_split_table;
SET @strtabcol = 'CREATE TEMPORARY TABLE temporary_split_table (';
SET @valcol = '';
WHILE(@colnum <= @no_of_cols + 1)
DO
SET @strtabcol = CONCAT(@strtabcol, 'COL', @colnum, ' VARCHAR(1000)', ',');
SET @colnum = @colnum + 1;
END WHILE;
SET @strtabcol = CONCAT(LEFT(@strtabcol, LENGTH(@strtabcol)-1), ')');
PREPARE stmt FROM @strtabcol;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @strcol = 'INSERT INTO temporary_split_table VALUES("';
SET @strcol = CONCAT(@strcol, @replacetosplit, '")');
PREPARE stmt FROM @strcol;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SELECT * FROM temporary_split_table;
END$$
DELIMITER ;
请不要忘记在使用上述SP后删除临时表temporary_split_table。
调用SP之上的方法是:
call split_procedure('Andy~22~US|Jane~24~Australia|Davis~30~UK|Nancy~32~Germany', '|', '~');