在Postgresql中从SELECT中插入多行

时间:2015-10-18 17:51:16

标签: sql postgresql

如PostgreSQL manual中所述,可以在单个INSERT语句中添加多行:

INSERT INTO films (code, title, did, date_prod, kind) VALUES
    ('6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
    ('6120', 'The Dinner Game', 140, DEFAULT, 'Comedy');

这样的嵌套SELECT查询也适用:

INSERT INTO films (code, title, did, date_prod, kind)
     SELECT table.code, 'Tampopo', 110, '1985-02-10', 'Comedy'
     FROM other_table AS table2;

然而,我似乎无法找到同时做到这两点的方法:

INSERT INTO films (code, title, did, date_prod, kind) 
SELECT
    (table.code + 100, 'abc', NULL, t2.date_prod, t2.kind),
    (table.code + 200, 'xyz', NULL, t2.date_prod, t2.kind)
FROM other_table AS t2;

如果other_table仅包含(61717 | 'Tampopo' | NULL | '1985-02-10' | 'Comedy'),则结果表将如下所示:

 code | title |  did |   date_prod  |   kind
--------------------------------------------------
61817 | 'abc' | NULL | '1985-02-10' | 'Comedy'
61917 | 'xyz' | NULL | '1985-02-10' | 'Comedy'

This fiddle应该进一步解释......

请你指点我错的地方。如果可能的话,我想避免在other_table AS t2中进行多次查找,因为它是VIEW,并且构建需要相当长的时间。

2 个答案:

答案 0 :(得分:2)

您可以使用INSERT INTO ... UNION ALL

INSERT INTO films (code, title, did, date_prod, kind)
SELECT t2.code + 100, t2.title, t2.did, t2.date_prod, t2.kind
FROM other_table AS t2
UNION ALL
SELECT t2.code + 200, t2.title, t2.did, t2.date_prod, t2.kind
FROM other_table AS t2;

答案 1 :(得分:2)

通常,您可以将selectunion一起使用:

insert into films (code, title, did, date_prod, kind) 
    select t2.code + 100, t2.title, NULL::float, t2.date_prod, t2.kind
    from other_table AS t2
union
    select t2.code + 200, t2.title, NULL::float, t2.date_prod, t2.kind
    from other_table AS t2;

在您描述的特定情况下,您可以使用unnest (array [])

insert into films (code, title, did, date_prod, kind) 
    select 
        unnest(array[t2.code + 100, t2.code + 200]), 
        t2.title, NULL::float, t2.date_prod, t2.kind
    from other_table AS t2