有没有办法用不同的 id 多次将同一行添加到 table 与 postgresql?

Is there a way to add the same row multiple times with different ids into a table with postgresql?

我试图将同一行的相同数据添加到我在 postgresql 中的 table x 次。有没有一种方法可以做到这一点而无需手动输入相同的值 x 次?我正在为 postgres 在 sql 中寻找 go[count] 的等价物...如果存在的话。

想法

生成给定大小的结果集并将其与要插入 x 次的记录交叉连接。仍然缺少的是正确 PK 值的生成。具体建议需要有关数据模型的更多详细信息。

查询

下面的示例查询假定您的 PK 值是自动生成的。

CREATE TABLE test ( id SERIAL, a VARCHAR(10), b VARCHAR(10) );

INSERT INTO test (a, b)
    WITH RECURSIVE Numbers(i) AS (
           SELECT 1
        UNION ALL
           SELECT i + 1
             FROM Numbers
            WHERE i < 5 -- This is the value `x`
    )
         SELECT adhoc.*
           FROM Numbers n
     CROSS JOIN ( -- This is the single record to be inserted multiple times
                   SELECT 'value_a' a
                        , 'value_b' b
                ) adhoc
 ;

this db fiddle 中查看实际效果。

备注/参考

该解决方案是从 here 中采用的,稍作修改(还有许多其他解决方案可以通过 SQL 分层/递归查询生成 x 连续数字,因此选择参考有点武断)。

使用函数generate_series(),例如:

insert into my_table
select id, 'alfa', 'beta'
from generate_series(1,4) as id;

db<>fiddle.

中测试