使用 INSERT ... ON CONFLICT DO NOTHING RETURNING 失败的行
Use INSERT ... ON CONFLICT DO NOTHING RETURNING failed rows
假设我有以下 table:
CREATE TABLE tags (
id int PK,
name varchar(255),
CONSTRAINT name_unique UNIQUE(name)
)
我需要一个查询来插入不存在的标签和所有请求标签的 return ID。考虑以下因素:
INSERT INTO tags (name) values ('tag10'), ('tag6'), ('tag11') ON CONFLICT DO NOTHING returning id, name
这个查询的输出是:
+---------------+
| id | name |
|---------------|
| 208 | tag10 |
|---------------|
| 209 | tag11 |
+---------------+
我需要的是在输出中包含 tag6
。
有点啰嗦,但我想不出别的了:
with all_tags (name) as (
values ('tag10'), ('tag6'), ('tag11')
), inserted (id, name) as (
INSERT INTO tags (name)
select name
from all_tags
ON CONFLICT DO NOTHING
returning id, name
)
select t.id, t.name, 'already there'
from tags t
join all_tags at on at.name = t.name
union all
select id, name, 'inserted'
from inserted;
来自 tags
的外部 select 看到 table 的快照,因为它是 在 插入新标签之前的样子。具有常量的第三列仅用于测试查询,以便可以识别哪些行已插入,哪些未插入。
有了这个table:
CREATE TABLE tags (
id serial PRIMARY KEY,
name text UNIQUE
);
只要查询中的值是唯一的,解决方法是:
INSERT INTO tags (name)
VALUES ('tag10'), ('tag6'), ('tag11')
ON CONFLICT DO UPDATE name = EXCLUDED.name RETURNING id, name;
假设我有以下 table:
CREATE TABLE tags (
id int PK,
name varchar(255),
CONSTRAINT name_unique UNIQUE(name)
)
我需要一个查询来插入不存在的标签和所有请求标签的 return ID。考虑以下因素:
INSERT INTO tags (name) values ('tag10'), ('tag6'), ('tag11') ON CONFLICT DO NOTHING returning id, name
这个查询的输出是:
+---------------+
| id | name |
|---------------|
| 208 | tag10 |
|---------------|
| 209 | tag11 |
+---------------+
我需要的是在输出中包含 tag6
。
有点啰嗦,但我想不出别的了:
with all_tags (name) as (
values ('tag10'), ('tag6'), ('tag11')
), inserted (id, name) as (
INSERT INTO tags (name)
select name
from all_tags
ON CONFLICT DO NOTHING
returning id, name
)
select t.id, t.name, 'already there'
from tags t
join all_tags at on at.name = t.name
union all
select id, name, 'inserted'
from inserted;
来自 tags
的外部 select 看到 table 的快照,因为它是 在 插入新标签之前的样子。具有常量的第三列仅用于测试查询,以便可以识别哪些行已插入,哪些未插入。
有了这个table:
CREATE TABLE tags (
id serial PRIMARY KEY,
name text UNIQUE
);
只要查询中的值是唯一的,解决方法是:
INSERT INTO tags (name)
VALUES ('tag10'), ('tag6'), ('tag11')
ON CONFLICT DO UPDATE name = EXCLUDED.name RETURNING id, name;