Write a Postgres Get or Create SQL Query

前端 未结 4 986
佛祖请我去吃肉
佛祖请我去吃肉 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:08

    If your columns participate in unique index constraint you can use an approach which is avaible since version 9.5:

    INSERT INTO mytable (color, brightness, size, age)
    VALUES ('X', 'Y', 'big', 'old')
    ON CONFLICT (color) DO NOTHING;
    

    (assuming you have unique index on color).

    Docs are gere: https://www.postgresql.org/docs/9.5/static/sql-insert.html

提交回复
热议问题