首页 > 解决方案 > 如何复制一行 50 次并在 MySQL 中使用自动增量 id 字段插入到同一个表中?

问题描述

在 MySQL 中,我试图复制具有自动增量列 ID=k 的行,并将其插入到同一个表中作为新行。假设表中有 10 行,因此执行查询后表中将有 500 行。

如何在单个查询中执行此操作?

标签: mysqlsql

解决方案


您可以使用递归 CTE 生成数字,然后基于该值插入:

insert into t ( . . . ) -- all columns besides the auto increment column
    with recursive cte as (
          select 1 as n
          union all
          select n + 1
          from cte
          where n < 49
         )
    select . . . -- all columns but the auto increment column
    from t cross join
         cte;

如果您想以 500 行结束,“49”可以是动态的。以上将现有行再插入 49 次。


推荐阅读