MySQL 數字輔助表去重 排序 行轉列

2021-07-25 15:47:36 字數 1281 閱讀 8441

一、需求

乙個欄位有多行記錄,查詢結果為去重排序的一行記錄,例如記錄值為:

1,2,4

1,4,5

2,323,56,67

3,4要求查詢結果為:

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

二、方案

使用數字輔助表實現

-- 建立數字輔助表  

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;

mysql 輔助表 MySQL 數字輔助表

數字輔助表是乙個包含從 1 到 n 的 n 個整數的簡單表,n 通常很大。因為數字輔助表是乙個非常強大的工具,可能經常需要在解決方案中用到它,所以建議建立乙個持久的數字輔助表,並根據需要填充一定資料量的值 mysql技術內幕 sql程式設計 建立數字輔助表 create table nums a i...

mysql數字輔助表 MySQL中數字輔助表的建立

數字輔助表是乙個只包含從1到n的n個整數的簡單表,n通常非常大 如何建立這樣乙個輔助表 1 我們可以通過下面這個方式建立 mysql create table nums a int unsigned not null primary key engine innodb query ok,0 rows...

去重排序問題

明明想在學校中請一些同學一起做一項問卷調查,為了實驗的客觀性,他先用計算機生成了n個1到1000之間的隨機整數 n 1000 對於其中重複的數字,只保留乙個,把其餘相同的數去掉,不同的數對應著不同的學生的學號。然後再把這些數從小到大排序,按照排好的順序去找同學做調查。請你協助明明完成 去重 與 排序...