如何在postgresql中插入并返回ID?

时间:2017-05-02 22:36:57

标签: .net postgresql

非常直接。我想我可以在冲突上做一个插入,然后做一个选择,但我喜欢一个衬垫。可能存在冲突,因为c1是唯一的。我想插入然后返回任何行的id为column1(c1)。

insert into foo(c1)
    VALUES(@c1, 0)
on conflict (c1) do nothing
RETURNING (select fooid from foo where c1=@c1)

2 个答案:

答案 0 :(得分:1)

当达到子句do nothing时,查询不返回任何行。在这种情况下返回fooid的唯一方法是执行冗余更新:

insert into foo (c1)
values (@c1)
on conflict (c1) do update set c1 = excluded.c1
returning fooid;

答案 1 :(得分:0)

您可以使用公用表表达式来避免冗余更新:

WITH    payload(c1) AS (
    SELECT @c1 -- your parameters here, you might have to CAST() them
), insert_action(c1) AS (
    INSERT INTO foo(c1)
        SELECT c1 FROM payload
    ON CONFLICT (c1) DO NOTHING
    RETURNING c1
)
SELECT  c1
FROM    insert_action
    RIGHT JOIN payload USING(c1);