在复制插入的单个查询中插入多个,将副本复制到Postgres中的copytable

时间:2017-09-20 06:22:38

标签: sql postgresql

我在单个查询中将多个记录插入到表中。但是,我在这里跳过重复的记录。我需要将这些重复的副本插入到具有相同结构的另一个表(copytable)中,而不是跳过这些记录。这两项活动都需要在一个声明中完成。即插入第一个表并将记录复制到第二个表

INSERT INTO manager.vin_manufacturer
(SELECT * FROM( VALUES
('935',' Citroën Brazil','Citroën'),
('ABC', 'Toyota', 'Toyota'),
('ZOM',' OM','OM')
) as tmp (vin_manufacturer_id, manufacturer_desc, make_desc)
WHERE NOT EXISTS (
SELECT 1 FROM manager.vin_manufacturer m where m.vin_manufacturer_id = 
tmp.vin_manufacturer_id)
)

1 个答案:

答案 0 :(得分:1)

您可以在一个语句中执行此操作,但您必须重复检测现有行的where条件(仅具有否定条件):

with tmp (vin_manufacturer_id, manufacturer_desc, make_desc) as (
  VALUES
    ('935',' Citroën Brazil','Citroën'),
    ('ABC', 'Toyota', 'Toyota'),
    ('ZOM',' OM','OM')
), inserted as (
  -- insert but skip duplicates
  INSERT INTO manager.vin_manufacturer (vin_manufacturer_id, manufacturer_desc, make_desc)
  SELECT vin_manufacturer_id, manufacturer_desc, make_desc
  FROM tmp
  WHERE NOT EXISTS (SELECT 1 
                    FROM manager.vin_manufacturer m 
                    where m.vin_manufacturer_id = tmp.vin_manufacturer_id)
  returning * -- return all inserted rows
)
-- insert the duplicates into a different table
insert into duplicates_table (vin_manufacturer_id, manufacturer_desc, make_desc)
select vin_manufacturer_id, manufacturer_desc, make_desc
from tmp
WHERE NOT EXISTS (select * 
                  from inserted i 
                  where i.vin_manufacturer_id = tmp.vin_manufacturer_id)