postgresql - PostgresQL 将一行复制到同一个表并更改一个值

标签 postgresql

我想插入一个新行,从原始行复制两个字段,并将最后一个字段更改为新值。这一切都在一张 table 上完成。

请原谅表格名称/字段,它们很长。

表 1 - alert_template_allocations

  • alert_template_allocation_id - pkey(忽略)
  • alert_template_allocation_io_id -(副本)
  • alert_template_allocation_alert_template_id -(副本)
  • alert_template_allocation_user_group_id -(更改为静态值)

表2-io

  • io_id - 复制属于站 222 的 io_id
  • io_station_id - 只想复制站 id = 222 的行

我的尝试

insert into alert_template_allocations
(alert_template_allocation_io_id,
alert_template_allocation_alert_template_id,
alert_template_allocation_user_group_id)
values 
(
    (Select at.alert_template_allocation_io_id,
    at.alert_template_allocation_alert_template_id
    from alert_template_allocations at join io i on
    i.io_id = at.alert_template_allocation_io_id
    and i.io_station_id = 222)
, 4);

最佳答案

使用INSERT INTO SELECT语法:

enter image description here

INSERT INTO alert_template_allocations (alert_template_allocation_io_id,
                                        alert_template_allocation_alert_template_id,
                                        alert_template_allocation_user_group_id)
SELECT at.alert_template_allocation_io_id,
       at.alert_template_allocation_alert_template_id,
       4
FROM alert_template_allocations at 
JOIN io i 
  ON i.io_id = at.alert_template_allocation_io_id
 AND i.io_station_id = 222;

关于postgresql - PostgresQL 将一行复制到同一个表并更改一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36695622/

相关文章:

postgresql - 通过 SymmetricDS 在 postgresql 数据库上配置多主机的正确方法是什么?

sql - 如何统计每个老师教过多少学生?

django - 从 Arduino 到 Django 数据库的 HTTP POST 数据

mysql - 如何避免在 postgreSQL 中对列名使用双引号?

sql - 对每个 UserId 实现限制的最快方法

python - SQLAlchemy 添加日期时间列,整数列转换为分钟间隔

postgresql - to_tsquery 查询电话号码

postgresql - 将超过 5000 万从 Pyspark df 写入 PostgresQL,最有效的方法

sql - 为什么在使用 json 数据执行 sql 插入查询后,postgres 表在每一列中都显示 Null?

postgresql - pgAdmin III 为什么查询结果被缩短了?