在 Postgresql 中从 SELECT 插入多行

n10*_*000 7 sql postgresql

如 PostgreSQL手册中所述,可以在单个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');
Run Code Online (Sandbox Code Playgroud)

SELECT像这样的嵌套查询也有效:

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

但是,我似乎无法想出一种同时进行的方法:

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;
Run Code Online (Sandbox Code Playgroud)

如果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'
Run Code Online (Sandbox Code Playgroud)

这个小提琴应该进一步解释它......

你能不能指出我哪里出错了。如果可能的话,我想避免多次查找,other_table AS t2因为它是一个VIEW并且需要相当长的时间来构建。

kli*_*lin 9

一般来说,你可以使用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;
Run Code Online (Sandbox Code Playgroud)

在您描述的特定情况下,您可以使用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
Run Code Online (Sandbox Code Playgroud)


Luk*_*zda 6

您可以使用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;
Run Code Online (Sandbox Code Playgroud)