PostgreSql INSERT FROM SELECT RETURNING ID

问题描述 投票:43回答:1

在PostgreSql 9.2.4中我有两个表:user (id, login, password, name)dealer (id, user_id)

我想插入两个表格,返回创建的经销商的ID。

目前我正在做两个查询:

WITH rows AS (
    INSERT INTO "user"
        (login, password, name)
    VALUES
        ('dealer1', 'jygbjybk', 'Dealer 1')
    RETURNING id
)
INSERT INTO dealer (user_id)
    SELECT id
    FROM rows;
SELECT currval('dealer_id_seq');

但是,我可以使用INSERT语句使用单个RETURNING查询来实现此功能吗?

sql postgresql insert postgresql-9.2
1个回答
68
投票

你只需要在你的RETURNING id上添加一个INSERT ... SELECT

WITH rows AS (...)
INSERT INTO dealer (user_id)
    SELECT id
    FROM rows
    RETURNING id;

但是:ぁzxswい

© www.soinside.com 2019 - 2024. All rights reserved.