首页 > 解决方案 > Postgres 在循环中为选定列中的所有值插入 N 行

问题描述

假设我将用户存储为

select * from users_t where user_name like 'ABC%';

id   user_name  
1    ABC1
2    ABC2
..   ..

现在我需要遍历所有user_name's 并将该数量的 INSERT 放入另一个表中,RECALLS_T. 所有其他列都是我定义的硬编码常量。

假设下表,RECALLS_T_ID_SEQ在 ID 上调用了一个序列:

id  created_by_user_name  field1   field2
1   ABC1                  Const1   Const2
2   ABC2                  Const1   Const2
..   ..                   ..       ..

如何在 Postgres 循环中插入这些?

附加问题另外,如果我需要为每个用户条目插入 X(比如 5)召回,该怎么办?假设它不是 1:1 映射,而是 5:1,其中 5 是硬编码的循环数。

标签: postgresql

解决方案


您可以selectinsert语句中使用:

insert into recalls_t (created_by_user_name, field1, field2)
select user_name, 'Const1', 'Const2'
from users_t 
where user_name like 'ABC%';

使用该函数generate_series()为 中的每个条目插入多行users_t。我添加了专栏step来说明这一点:

insert into recalls_t (created_by_user_name, field1, field2, step)
select user_name, 'Const1', 'Const2', step
from users_t 
cross join generate_series(1, 3) as step
where user_name like 'ABC%'
returning *

 id | created_by_user_name | field1 | field2 | step 
----+----------------------+--------+--------+------
  1 | ABC1                 | Const1 | Const2 |    1
  2 | ABC2                 | Const1 | Const2 |    1
  3 | ABC1                 | Const1 | Const2 |    2
  4 | ABC2                 | Const1 | Const2 |    2
  5 | ABC1                 | Const1 | Const2 |    3
  6 | ABC2                 | Const1 | Const2 |    3
(6 rows)

Db<>fiddle中的现场演示。


推荐阅读