Write a Postgres Get or Create SQL Query

前端 未结 4 978
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-13 12:42

I want to write a single Postgres SQL statement that says look for a user with color X and brightness Y. If that user exists, return all of its row data. If not, create a new

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-13 13:17

    with sel as (
        select color, brightness, size, age
        from mytable
        where color = 'X' and brightness = 'Y'
    ), ins as (
        insert into mytable (color, brightness, size, age)
        select 'X', 'Y', 6.2, 40
        where not exists (
            select 1 from sel
        )
        returning color, brightness, size, age
    )
    select color, brightness, size, age
    from ins
    union
    select color, brightness, size, age
    from sel
    

提交回复
热议问题