将PostgreSQL表中的一行复制到同一张表并更改一个值

3

我想要插入一行新数据,该行将原始行的两个字段复制,并更改最后一个字段的值。这一切都在一个表中完成。

请原谅表名/字段非常长。

表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_ids
  • 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);
1个回答

3

使用 INSERT INTO SELECT 语法:

输入图像描述

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接