zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Tomcat安装配置
    重新捡起手中的笔
    如何拥有一套自己的信用卡分销系统
    关于信用卡分销系统的简单介绍
    jQuery 基础教程(第3版) ---第十章习题答案
    jQuery 基础教程(第3版) ---第九章习题答案
    jQuery 基础教程(第3版) ---第八章习题答案
    jQuery 基础教程(第3版) ---第七章习题答案
    jQuery 基础教程(第3版) ---第六章习题答案
    jQuery 基础教程(第3版) ---第五章习题答案
  • 原文地址:https://www.cnblogs.com/dalianpai/p/14334871.html
Copyright © 2011-2022 走看看