循环唯一插入到临时表mysql存储过程中

brccelvz  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(369)

我有两张这样的table:

Table 1
    Type 1 | Type 2 | Type 3 | ...
       1   |   3    |    0   | ...

Table 2
    Type 1 | Type 2 | Type 3 | ...
       3   |   2    |    1   | ...

我想把它们组合成这样一个临时表:

Temporary Table
UID |  Type  | Table
 1  | Type 1 |   1
 2  | Type 2 |   1
 3  | Type 2 |   1
 4  | Type 2 |   1
 7  | Type 1 |   2
 8  | Type 1 |   2
 9  | Type 1 |   2
10  | Type 2 |   2
11  | Type 2 |   2

从本质上讲,表1和表2中的数字是总计,我想在这个临时表中将它们分解成单独的行。
我开始从两个表中进行选择,并将值存储到临时变量中。然后我将遍历每个变量并插入临时表。但我有大约15列每表,必须有一个更简单的方法来做到这一点。我只是不知道是什么。
有人对此有什么见解吗?我对mysql存储过程的了解非常有限。

vcirk6k6

vcirk6k61#

不知道有什么简单的方法。一个选择是有一个数字表。这里有一个快速的方法,以获得1-10在一个小时 common-table-expression (根据需要更改)。
那你就可以了 join 到每个表和每个类型,使用 union all 对于每个子集。这是一个简明的版本:

with numbers as (select 1 n union all select 2 union all 
   select 3 union all select 4 union all select 5 union all
   select 6 union all select 7 union all select 8 union all
   select 9 union all select 10)
select 'type1' as type, '1' as tab
from numbers n join table1 t on n.n <= t.type1
union all 
select 'type2' as type, '1' as tab
from numbers n join table1 t on n.n <= t.type2
union all
select 'type1' as type, '2' as tab
from numbers n join table2 t on n.n <= t.type1
union all 
select 'type2' as type, '2' as tab
from numbers n join table2 t on n.n <= t.type2

演示小提琴

相关问题