2016-04-18 10 views
1

元の行から2つのフィールドをコピーし、最後のフィールドを新しい値に変更する新しい行を挿入したいとします。これはすべて1つのテーブルで行われます。PostgresSQL同じテーブルに行をコピーして1つの値を変更する

表の名前/フィールドは間違いありません。長すぎます。

表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_station_idに属しコピーio_ids - したい行のみをコピーする場所をステーション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

使用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; 
+1

完璧、ありがとう! –

関連する問題