Insert if not exists, else return id in postgresql

后端 未结 3 1966
無奈伤痛
無奈伤痛 2020-11-29 18:51

I have a simple table in PostgreSQL that has three columns:

  • id serial primary key
  • key varchar
  • value varchar

I have already see

3条回答
  •  星月不相逢
    2020-11-29 19:26

    with vals as (
      select 'key5' as key, 'value2' as value
    )
    insert into Test1 (key, value)
    select v.key, v.value
    from vals as v
    where not exists (select * from Test1 as t where t.key = v.key and t.value = v.value)
    returning id
    

    sql fiddle demo

提交回复
热议问题