我在 PostgreSQL 中有一个包含三列的简单表:
- id序列主键
- 键变量
- 值变量
我已经在 SO 上看到这个问题:Insert, on duplicate update in PostgreSQL?但我想知道如果它存在,如何获取 id,而不是更新。如果标准做法总是“插入”或“如果存在则更新”,这是为什么呢?执行 SELECT (LIMIT 1) 的成本是否大于执行 UPDATE 的成本?
我有以下代码
INSERT INTO tag
("key", "value")
SELECT 'key1', 'value1'
WHERE
NOT EXISTS (
SELECT id,"key","value" FROM tag WHERE key = 'key1' AND value = 'value1'
);
它的工作原理是如果存在则不插入,但我想获取 id。是否有“RETURNING id”子句或类似的东西可供我使用?
最佳答案
是的,有返回
INSERT INTO tag ("key", "value")
SELECT 'key1', 'value1'
WHERE NOT EXISTS (
SELECT id, "key", "value"
FROM node_tag
WHERE key = 'key1' AND value = 'value1'
)
returning id, "key", "value"
如果行已经存在则返回
with s as (
select id, "key", "value"
from tag
where key = 'key1' and value = 'value1'
), i as (
insert into tag ("key", "value")
select 'key1', 'value1'
where not exists (select 1 from s)
returning id, "key", "value"
)
select id, "key", "value"
from i
union all
select id, "key", "value"
from s
如果该行不存在,它将返回插入的行,否则返回现有的行。
顺便说一句,如果“键”/“值”对使其唯一,那么它就是主键,并且不需要 id 列。除非“键”/“值”对中的一个或两个可以为空。
关于postgresql - 如果不存在则插入,否则在 postgresql 中返回 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18192570/