Postgresql 选择比insert所需的列更多的列,以便在返回语句中使用
为了举例说明,以下是Postgres 9.6中的一些表格:Postgresql 选择比insert所需的列更多的列,以便在返回语句中使用,postgresql,sql-insert,bulkinsert,sql-returning,Postgresql,Sql Insert,Bulkinsert,Sql Returning,为了举例说明,以下是Postgres 9.6中的一些表格: 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 我想在peo
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中插入多个值,并将组名返回给我。我已经有了人名(2)。以下代码可以工作,但不返回名称
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的表达式比目标列多。是否有任何方法可以将组表中的name
返回给我(通过RETURNING
子句)?我知道我传入了组名,但是上面的查询将无法插入'xxx'(重复键)和'notthere'(没有这样的组),因此它将只返回'yyy'。理想情况下,我希望能够知道某些插入失败的原因,但我会尽我所能
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