postgresql - 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 是硬编码的循环数。
解决方案
您可以select
在insert
语句中使用:
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中的现场演示。
推荐阅读
- android - 每次在 Java Android Studio 中都需要在 for 循环中更改变量名
- python - Mongo凌乱的DOB字符串字段到年龄
- python - 将先前计费数据的行扩展为列。蟒蛇熊猫
- python - 以所需模式打印列表
- python - 如何在另一个网页上显示基于 python 的 GUI 和 PHP 网页的输出?
- javascript - vanila JS轮播中的mouseenter clearInterval()
- python - AttributeError:'bytes' 对象在 MultiFernet 中没有属性 'encrypt_at_time'
- javascript - 从另一个组件更新组件状态的最简单方法是什么?可以说组件是兄弟姐妹吗?
- python - Python函数:为什么我们可以在函数中定义变量/对象之前引用它?
- visual-studio-code - [VsCode 远程 SSH]如何解决“无法建立与 XXX.XXX.XXX.XXX 的连接:下载 VS Code 服务器失败”?