SQL 如果 Postgres 中不存在记录,则插入值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13918449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:39:35  来源:igfitidea点击:

Insert values if records don't already exist in Postgres

sqlpostgresql

提问by Matt York

I'd like to get this working, but Postgres doesn't like having the WHEREclause in this type of insert.

我想让这个工作,但 Postgres 不喜欢WHERE在这种类型的插入中有子句。

  INSERT INTO keys(name, value) VALUES
    ('blah', 'true')
  WHERE NOT EXISTS (
    SELECT 1 FROM keys WHERE name='blah'
  );

回答by VoidMain

In Postgres, you can use a subquery to conditionally insert:

在 Postgres 中,您可以使用子查询来有条件地插入:

INSERT INTO keys(name, value) 
    SELECT 'blah', 'true'
    WHERE NOT EXISTS (
        SELECT 1 FROM keys WHERE name='blah'
    );

hope that helps.-

希望有帮助。-

回答by MK Yung

In Postgresql 9.5 you can now use on conflict do nothing

在 Postgresql 9.5 中,您现在可以使用 on conflict do nothing

insert into KEYS (name, value) values (
'blah', 'true') on conflict (name) do nothing;