我想为存在于db:select id * from users中的每个用户在profit表中插入新的行。用户的数量是动态的,所以我需要获取所有的用户。我需要postgres sql中的一些循环。我自己解决这个问题有问题。应该是这样的:
select id * from users as user_ids
for (each userId in user_ids) {
insert into profit (user_id, value) values (userId, 23);
}我能向你寻求帮助吗?我已经问了很多问题了:
Insert new row with data computed from other rows
postgresSQL insert multiple rows, of id returned from select queries
到目前为止还没有运气
发布于 2019-10-11 15:46:50
在使用SQL时,在“循环”中思考几乎总是错误的。你需要从集合的角度思考,以及如何对它们进行操作。SQL语句准确地描述了这一点:如何检索集合以及如何处理这组行。
在这种情况下,您可以使用SELECT语句作为INSERT的源:
insert into profit (user_id, value)
select id, 23
from users;请注意,在本例中没有values子句。
https://stackoverflow.com/questions/58336518
复制相似问题