Mysql 逗號分隔行列轉換總結

來源:互聯網
上載者:User

標籤:root   substr   命令   預設   預存程序   turn   efault   笛卡爾   過程   

方法一
預存程序實現:

 
-- 修改結束符,防止在mysql命令列中預設分號直接運行
delimiter $$

 
-- 建立一個計算拆分後字串的個數函數
drop function if exists calc_length $$
create function calc_length(str varchar(200), splitstr varchar(5)) returns int(11)
begin 
return length(str)-length(replace(str, splitstr, ‘‘))+1;
end $$

 
-- 建立一個類比的split拆分字串的函數
drop function if exists split_string $$
create definer=‘root‘@‘localhost‘ function split_string(str varchar(200), splitstr varchar(5), strindex int) returns varchar(255)
begin
declare result varchar(255) default ‘‘;
set result =reverse(substring_index( reverse(substring_index(str, splitstr, strindex)), splitstr, 1));
return result;
end $$

 
-- 建立一個預存程序
drop procedure if exists proce_split $$
create procedure proce_split()
begin
declare cnt int default 0;
declare i int default 0;
declare str varchar(2000) default ‘‘;
select name into str from table1 where id =2;
set cnt = calc_length(str, ‘,‘);

 
drop table if exists table2;
create table2(id int not null, name varchar(255) not null) default charset=utf8;

 
while i < cnt 
do 
set i = i+1;
insert into table(id, name) values(i, split_string(str,‘,‘, i));
end while;
end $$

 
方法二:
笛卡爾積實現:

 
select a.ID,substring_index(substring_index(a.loginName,‘,‘,b.help_topic_id+1),‘,‘,-1) 
from 
account a
join
mysql.help_topic  b
on b.help_topic_id < (length(a.loginName)- length(replace(a.loginName,‘,‘,‘‘))+1)
order by a.ID;

Mysql 逗號分隔行列轉換總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.