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

  • 相关阅读:
    docker安装和hub
    sql获取时间、年龄
    在eclipse中配置Tomcat时,出现“Cannot create a server using the selected type”的错误。
    ajax简单做html查询删除(鲜花)
    java使用jsp建立项目+视频
    java根据数据库自动生成代码
    java连接数据库增删改查公共方法
    制作二维码java
    富文本编译器
    java字符串类型和时间类型的转换
  • 原文地址:https://www.cnblogs.com/dalianpai/p/14334871.html
Copyright © 2011-2022 走看看