选择更多列以进行插入以在RETURNING语句中使用

时间:2017-04-25 18:50:43

标签: 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

我想在people_in_group中插入多个值,并将组名返回给我。我已经有了person_id(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 has more expressions than target columns。有没有办法让groups表中的name返回给我(通过RETURNING子句)?我知道我传入了组名,但上面的查询将无法插入'xxx'(重复键),'不存在'(没有这样的组),所以它只会返回'yyy'。理想情况下,我希望能够知道某些INSERTs失败的原因,但我会采取我能得到的结果。

1 个答案:

答案 0 :(得分:1)

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