PostgreSql INSERT FROM SELECT RETURNING ID

时间:2013-10-03 19:12:02

标签: sql postgresql insert postgresql-9.2

在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查询实现此功能吗?

2 个答案:

答案 0 :(得分:66)

您只需向RETURNING id添加INSERT ... SELECT

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

演示:http://sqlfiddle.com/#!12/75008/1

答案 1 :(得分:0)

出于我的目的,我需要在一个变量中使用它,所以我这样做了:

INSERT INTO dealer (user_id)
    SELECT id
    FROM rows
    RETURNING id INTO l_dealerid;