MySQL 循环内循环以转置记录
MySQL Loop within a Loop to Transpose records
我有一个包含字段(id、数量、productId、customerId、deliveryDate)的交货 table。需要在每个产品上放置一个序列化标签,并维护标签、产品、客户和交货日期的日志。 tagLogtable自动递增,id代表标签序列号
Delivery Table
id quantity productId customerId deliveryDate
2085 4 10197 245 2020-06-05
2085 2 10433 245 2020-06-05
我想遍历交货 table(尚未标记的地方),并为每一行在 tagLog 中为数量字段中的数字创建一个单独的记录。比如这两条Delivery记录应该在tagLog中创建6条记录table.
tagLog
tagId productId customerId deliveryDate
20890 10197 245 2020-06-05
20891 10197 245 2020-06-05
20892 10197 245 2020-06-05
20893 10197 245 2020-06-05
20894 10433 245 2020-06-05
20895 10433 245 2020-06-05
任何关于内部循环构造的建议都将不胜感激。
SQL 是一种基于集合的 语言,在处理循环方面效率不高。
如果你是运行 MySQL 8.0,你可以通过递归查询来实现(这仍然是一个迭代过程,但比存储过程中的循环具有更好的性能):
with recursive cte as (
select id, productId, customerId, deliveryDate, quantity
from delivery
union all
select id, productId, customerId, deliveryDate, quantity - 1
from cte
where quantity > 0
)
select
row_number() over(order by id) tagId,
productId,
customerId,
deliveryDate
from cte
不清楚您想使用哪种方法生成 tagId
。这为您提供了一个始终递增的数字,该数字从 1
开始,并且同一原始 id
的记录是连续的。
我有一个包含字段(id、数量、productId、customerId、deliveryDate)的交货 table。需要在每个产品上放置一个序列化标签,并维护标签、产品、客户和交货日期的日志。 tagLogtable自动递增,id代表标签序列号
Delivery Table
id quantity productId customerId deliveryDate
2085 4 10197 245 2020-06-05
2085 2 10433 245 2020-06-05
我想遍历交货 table(尚未标记的地方),并为每一行在 tagLog 中为数量字段中的数字创建一个单独的记录。比如这两条Delivery记录应该在tagLog中创建6条记录table.
tagLog
tagId productId customerId deliveryDate
20890 10197 245 2020-06-05
20891 10197 245 2020-06-05
20892 10197 245 2020-06-05
20893 10197 245 2020-06-05
20894 10433 245 2020-06-05
20895 10433 245 2020-06-05
任何关于内部循环构造的建议都将不胜感激。
SQL 是一种基于集合的 语言,在处理循环方面效率不高。
如果你是运行 MySQL 8.0,你可以通过递归查询来实现(这仍然是一个迭代过程,但比存储过程中的循环具有更好的性能):
with recursive cte as (
select id, productId, customerId, deliveryDate, quantity
from delivery
union all
select id, productId, customerId, deliveryDate, quantity - 1
from cte
where quantity > 0
)
select
row_number() over(order by id) tagId,
productId,
customerId,
deliveryDate
from cte
不清楚您想使用哪种方法生成 tagId
。这为您提供了一个始终递增的数字,该数字从 1
开始,并且同一原始 id
的记录是连续的。