循环唯一插入临时 table MySql 存储过程

Loop unique insert into temporary table MySql stored procedure

我有两个 table 看起来像这样:

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

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

我想将它们组合成一个临时的 table,如下所示:

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

本质上,tables 1 和 2 中的数字是总计,我想在此临时 table.

中将它们分成单独的行

我开始沿着从 table 中选择并将值存储到临时变量中的路径前进。然后我打算遍历每个变量并插入临时 table。但是每个 table 我有大约 15 列,必须有一种更简单的方法来做到这一点。我只是不知道它是什么。

有没有人对此有任何见解?我对 MySql 存储过程的了解非常有限。

不确定执行此操作的简单方法。一种选择是使用数字 table。这是在 common-table-expression 中获得 1-10 的快速方法(根据需要更改)。

然后你可以对每个 table 和每个类型 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