SELECT or INSERT a row in one command

前端 未结 4 1917
囚心锁ツ
囚心锁ツ 2020-12-07 20:28

I\'m using PostgreSQL 9.0 and I have a table with just an artificial key (auto-incrementing sequence) and another unique key. (Yes, there is a reason for this table. :)) I w

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 21:15

    Have you tried to union it?


    Edit - this requires Postgres 9.1:

    create table mytable (id serial primary key, other_key varchar not null unique);
    
    WITH new_row AS (
    INSERT INTO mytable (other_key)
    SELECT 'SOMETHING'
    WHERE NOT EXISTS (SELECT * FROM mytable WHERE other_key = 'SOMETHING')
    RETURNING *
    )
    SELECT * FROM new_row
    UNION
    SELECT * FROM mytable WHERE other_key = 'SOMETHING';
    

    results in:

     id | other_key 
    ----+-----------
      1 | SOMETHING
    (1 row)
    

提交回复
热议问题