• mysql一行转多行加上一行转多列


    看到群里有人有个sql不会写,平时mysql复杂写的少,就简单写了写。虽然写的很烂,但是思路还可以。。

    create table t1(
        xid varchar(10) , 
        Name varchar(20), 
        Code varchar(100)  
    );
    
    create table t2(
        yid varchar(10) , 
        Name varchar(20), 
        je varchar(10)    
    );
    
    											
    insert into t1(xid,Name,Code) values('1','a','[a1][1]+[b2][2]');	
    insert into t1(xid,Name,Code) values('2','b','[b2][3]');			
    insert into t1(xid,Name,Code) values('3','c','[c3][3]+[a1][1]');	
    
    insert into t2(yid,name,je) values ('a1','瓜子','1.5');
    insert into t2(yid,name,je) values ('b2','花生','1');
    insert into t2(yid,name,je) values ('c3','板栗','2');
    

    他需要这样的结果:

    image-20210127142552833

    思路如下:

    select t.xid,t.name,REPLACE(REPLACE(REPLACE(REPLACE(t.code,"]+[",","),"][",":"),"[",""),"]","") as rn from t1 t 
    

    image-20210127142720899

    select t.xid,t.name,substring_index(
            substring_index(
                t.rn,
                ',',
                b.help_topic_id + 1
            ),
            ',' ,- 1
        ) AS rn from (select t.xid,t.name,REPLACE(REPLACE(REPLACE(REPLACE(t.code,"]+[",","),"][",":"),"[",""),"]","") as rn from t1 t )t
    JOIN mysql.help_topic b ON b.help_topic_id <
    (length(t.rn) - length( replace(t.rn, ',', '')  ) + 1)
    

    image-20210127142811326

    select tt.xid,tt.name,SUBSTR(tt.rn,1,2) as yid,SUBSTR(tt.rn,4,LENGTH(tt.rn)) as num from 
    (select t.xid,t.name,substring_index(
            substring_index(
                t.rn,
                ',',
                b.help_topic_id + 1
            ),
            ',' ,- 1
        ) AS rn from (select t.xid,t.name,REPLACE(REPLACE(REPLACE(REPLACE(t.code,"]+[",","),"][",":"),"[",""),"]","") as rn from t1 t )t
    JOIN mysql.help_topic b ON b.help_topic_id <
    (length(t.rn) - length( replace(t.rn, ',', '')  ) + 1)) tt
    

    
    select t3.xid,t3.name,t2.`Name`,t2.je,t3.num from 
    (select tt.xid,tt.name,SUBSTR(tt.rn,1,2) as yid,SUBSTR(tt.rn,4,LENGTH(tt.rn)) as num from 
    (select t.xid,t.name,substring_index(
            substring_index(
                t.rn,
                ',',
                b.help_topic_id + 1
            ),
            ',' ,- 1
        ) AS rn from (select t.xid,t.name,REPLACE(REPLACE(REPLACE(REPLACE(t.code,"]+[",","),"][",":"),"[",""),"]","") as rn from t1 t )t
    JOIN mysql.help_topic b ON b.help_topic_id <
    (length(t.rn) - length( replace(t.rn, ',', '')  ) + 1)) tt)t3
    INNER JOIN t2 
    on t3.yid = t2.yid
    

    image-20210127142903098

  • 相关阅读:
    我的插件框架·前传
    在OpenSUSE中听歌
    ASP.NET MVC 3.0 源码阅读手记(1)
    Mono on Linux 开发与实践札记(1)
    探讨对Web控件的异常处理
    进销存管理中负库存产生的原因以及对应措施
    看了一篇不错的文章 使用 UTF8 对 XML 文档进行编码
    进销存管理中对红冲处理的误区
    Ajax学习笔记(2) 一定要用XML吗?
    打造自己的Html文本编辑控件
  • 原文地址:https://www.cnblogs.com/dalianpai/p/14334871.html
Copyright © 2020-2023  润新知