【问题标题】:How to insert new row with id from other table in loop with Postgressql如何使用 Postgresql 在循环中从其他表中插入带有 id 的新行
【发布时间】:2019-10-11 07:45:06
【问题描述】:

我想在profit 表中为数据库中存在的每个用户插入新行:select id * from users。用户数量是动态的,所以我需要全部获取。我需要 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

目前没有运气

【问题讨论】:

    标签: sql postgresql sql-insert


    【解决方案1】:

    在使用 SQL 时,考虑“循环”几乎总是错误的。你需要从集合以及如何操作它们的角度来思考。 SQL 语句准确地描述了这一点:如何检索一个集合以及如何处理该集合。

    在这种情况下,您可以使用 SELECT 语句作为 INSERT 的源:

    insert into profit (user_id, value) 
    select id, 23
    from users;
    

    请注意,在这种情况下,您没有 values 子句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      相关资源
      最近更新 更多