选择比插入所需更多的列以用于 RETURNING 语句
Selecting more columns than necessary for insert for use in RETURNING statement
为了说明,下面是 Postgres 9.6 中的一些 table:
people
id | name
----+------
1 | a
2 | b
3 | c
4 | d
groups
id | name
----+-------
10 | xxx
20 | yyy
30 | zzz
people_in_group
person_id | group_id
----------+-------
1 | 10
2 | 10
我想在 people_in_group 中插入多个值,并将组名 return 发送给我。我已经有了 person_id (2)。以下有效,但不 return 名称。
INSERT INTO people_in_group(person_id, group_id)
SELECT '2' AS person_id, id as group_id FROM groups
WHERE name IN ('xxx', 'yyy', 'not there')
ON CONFLICT DO NOTHING
RETURNING *;
如果我将 name
添加到 SELECT
子句,我将得到 INSERT has more expressions than target columns
。有什么方法可以让 table return 组的 name
发给我(通过 RETURNING
子句)?我知道我传入了组名,但是上面的查询将无法插入 'xxx'(重复键)和 'not there'(没有这样的组),所以它只会 return 'yyy'。理想情况下,我希望能够知道某些 INSERTs
失败的原因,但我会尽力而为。
with i as (
insert into people_in_group(person_id, group_id)
select '2' as person_id, id as group_id
from groups
where name in ('xxx', 'yyy', 'not there')
on conflict do nothing
returning *
)
select i.person_id, i.group_id, g.name
from i inner join groups g on g.id = i.group_id
为了说明,下面是 Postgres 9.6 中的一些 table:
people
id | name
----+------
1 | a
2 | b
3 | c
4 | d
groups
id | name
----+-------
10 | xxx
20 | yyy
30 | zzz
people_in_group
person_id | group_id
----------+-------
1 | 10
2 | 10
我想在 people_in_group 中插入多个值,并将组名 return 发送给我。我已经有了 person_id (2)。以下有效,但不 return 名称。
INSERT INTO people_in_group(person_id, group_id)
SELECT '2' AS person_id, id as group_id FROM groups
WHERE name IN ('xxx', 'yyy', 'not there')
ON CONFLICT DO NOTHING
RETURNING *;
如果我将 name
添加到 SELECT
子句,我将得到 INSERT has more expressions than target columns
。有什么方法可以让 table return 组的 name
发给我(通过 RETURNING
子句)?我知道我传入了组名,但是上面的查询将无法插入 'xxx'(重复键)和 'not there'(没有这样的组),所以它只会 return 'yyy'。理想情况下,我希望能够知道某些 INSERTs
失败的原因,但我会尽力而为。
with i as (
insert into people_in_group(person_id, group_id)
select '2' as person_id, id as group_id
from groups
where name in ('xxx', 'yyy', 'not there')
on conflict do nothing
returning *
)
select i.person_id, i.group_id, g.name
from i inner join groups g on g.id = i.group_id