zoukankan      html  css  js  c++  java
  • Mysql 逗号分隔行列转换总结

    方法一
    存储过程实现:
    
    
    -- 修改结束符,防止在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;
  • 相关阅读:
    PowerDesigner中Table视图同时显示Code和Name
    sql语句 生成数据库表
    业务流程图
    物理模型图-数据库图
    观察者模式
    UML的九种图
    路由器工作原理
    web项目中处理捕获异常统一处理
    java中volatile、synchronized
    linux 安装软件的几种方法
  • 原文地址:https://www.cnblogs.com/fengyingwang/p/7591221.html
Copyright © 2011-2022 走看看