首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >MySQL 数字辅助表去重、排序、行转列

MySQL 数字辅助表去重、排序、行转列

作者头像
用户1148526
发布2019-05-25 19:46:05
发布2019-05-25 19:46:05
2.9K0
举报
文章被收录于专栏:Hadoop数据仓库Hadoop数据仓库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1433217

一、需求

一个字段有多行记录,查询结果为去重排序的一行记录,例如记录值为:

1,2,4

1,4,5

2,3

23,56,67

3,4

要求查询结果为:

1,2,3,4,5,23,56,67

二、方案

使用数字辅助表实现

代码语言:javascript
复制
-- 建立数字辅助表  
create table nums (  
    a int not null primary key  
);  
delimiter $$  
create procedure pFastCreateNums(cnt int)  
begin  
    declare s int default 1;  
    truncate table nums;  
    insert into nums select s;  
    while s<=cnt do  
        insert into nums select a+s from nums where a+s <= cnt;  
        set s=s*2;  
    end while;  
    commit;  
end $$  
delimiter ;  
call pFastCreateNums(1000000);  
  
-- 建立测试表  
create table t1 (  
    a varchar(100)  
);  
insert into t1 values('1,2,4'),('1,4,5'),('2,3'),('23,56,67'),('3,4');  
commit;  
  
-- 查询  
select   
    group_concat(a)  
from  
    (select   
        a  
    from  
        (select   
        cast(substring_index(substring_index(t1.a, ',', nums.a), ',', - 1)  
                as unsigned) a  
    from  
        t1, nums  
    where  
        nums.a <= length(t1.a) - length(replace(t1.a, ',', '')) + 1) t  
    group by a) t1;  
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016年12月27日,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档