2017-04-25 48 views
0

爲了說明,這裏是Postgres的9.6一些表:選擇更多的列比必要插入用於RETURNING聲明

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 *; 

如果我添加nameSELECT條款,我會得到INSERT has more expressions than target columns。有沒有辦法將name從組表中退回給我(通過RETURNING條款)?我知道我傳入了組名,但上面的查詢將無法插入'xxx'(重複鍵)和'不存在'(沒有這樣的組),所以它只會返回'yyy'。理想情況下,我希望能夠知道爲什麼某些INSERTs失敗,但我會盡我所能。

回答

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