2

假设我有下表:

CREATE TABLE tags (
    id int PK,
    name varchar(255),
    CONSTRAINT name_unique UNIQUE(name)
)

我需要一个查询来插入不存在的标签并返回所有请求标签的 id。考虑以下:

INSERT INTO tags (name) values ('tag10'), ('tag6'), ('tag11') ON CONFLICT DO NOTHING returning id, name

此查询的输出是:

+---------------+
|  id   |  name |
|---------------|
|  208  | tag10 |
|---------------|
|  209  | tag11 |
+---------------+

我需要的是tag6输出。

4

2 回答 2

10

有点冗长,但我想不出其他任何东西:

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;

外部 select fromtags会看到插入新标签之前的表快照。带有常量的第三列仅用于测试查询,以便可以识别插入了哪些行,哪些没有插入。

于 2016-02-08T08:54:18.650 回答
1

有了这张表:

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;
于 2018-03-06T13:16:21.563 回答