【问题标题】:Selecting more columns than necessary for insert for use in RETURNING statement选择多于插入所需的列以在 RETURNING 语句中使用
【发布时间】:2017-04-25 18:50:42
【问题描述】:

为了说明,这里是 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。有什么方法可以让组表中的name 返回给我(通过RETURNING 子句)?我知道我传入了组名,但是上面的查询将无法插入“xxx”(重复键)和“不存在”(没有这样的组),所以它只会返回“yyy”。理想情况下,我想知道某些INSERTs 失败的原因,但我会尽我所能。

【问题讨论】:

    标签: postgresql sql-insert bulkinsert sql-returning


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      相关资源
      最近更新 更多