Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
循环中的MySQL循环,用于转置记录_Mysql_Sql_Loops_Transpose_Recursive Query - Fatal编程技术网

循环中的MySQL循环,用于转置记录

循环中的MySQL循环,用于转置记录,mysql,sql,loops,transpose,recursive-query,Mysql,Sql,Loops,Transpose,Recursive Query,我有一个带有字段(id、数量、productId、customerId、deliveryDate)的交货表。要求在每个产品上放置一个序列化标签,并维护标签、产品、客户和交付日期的日志。tagLog表是自动递增的,id表示标记序列号 Delivery Table id quantity productId customerId deliveryDate 2085 4 10197 245 2020-06-05 20

我有一个带有字段(id、数量、productId、customerId、deliveryDate)的交货表。要求在每个产品上放置一个序列化标签,并维护标签、产品、客户和交付日期的日志。tagLog表是自动递增的,id表示标记序列号

Delivery Table
id    quantity   productId     customerId     deliveryDate 
2085     4        10197          245          2020-06-05
2085     2        10433          245          2020-06-05
我想在交货表(尚未标记的地方)中循环,并为每一行在tagLog中为数量字段中的数字创建一条单独的记录。例如,这两条交付记录应在tagLog表中创建6条记录

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,那么可以通过递归查询(这仍然是一个迭代过程,但性能比存储过程中的循环要好):

不清楚要使用哪种方法生成
tagId
。这将为您提供一个始终递增的数字,该数字从
1开始,并且相同原始
id
的记录是连续的。

SQL是一种基于集合的语言,在处理循环时效率不高

如果您运行的是MySQL 8.0,那么可以通过递归查询(这仍然是一个迭代过程,但性能比存储过程中的循环要好):


不清楚要使用哪种方法生成
tagId
。这将为您提供一个从
1
开始的始终递增的数字,其中相同原始
id
的记录是连续的。

请参阅,我希望使用自动递增来序列化标记。我可能有缺陷的标签等问题,但我可以在这些情况下编辑。谢谢你在这方面的帮助。我希望使用自动递增来序列化标记。我可能有缺陷的标签等问题,但我可以在这些情况下编辑。谢谢你在这方面的帮助。
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