循环唯一插入到临时表MySql存储过程中
我有两张像这样的桌子:循环唯一插入到临时表MySql存储过程中,mysql,stored-procedures,temp-tables,Mysql,Stored Procedures,Temp Tables,我有两张像这样的桌子: 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 |
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
我想将它们合并到一个临时表中,如下所示:
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存储过程的了解非常有限。不确定是否有一种简单的方法可以做到这一点。一个选择是有一个数字表。下面是一个快速方法,可以根据需要更改公共表表达式中的1-10 然后,您可以使用UNIONALL对每个子集连接到每个表和每个类型。以下是一个简明版本:
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
Welp,我不太明白,但是我很欣赏这个演示和关键词。我将开始研究表的“UNIONALL”和“join”,并对其进行解释。非常感谢。我应该添加“WITH”子句,它只适用于MySQL 8.0。