SQL 如果一行不存在插入,否则不要在 postgres 中插入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15204621/
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 14:02:34  来源:igfitidea点击:

If a row does not exists insert else don't insert in postgres

sqlpostgresql

提问by JumpOffBox

I need to check if a row exists or not. If it does not exist, it should be inserted.

我需要检查一行是否存在。如果不存在,则应插入。

This is in postgresand I am trying to insert row through a shell script. When I run the script it does not show error but it does not insert into table even though no matching row is present.

这是在postgres,我正在尝试通过 shell 脚本插入行。当我运行脚本时,它不会显示错误,但即使不存在匹配的行,它也不会插入到表中。

回答by Andres Olarte

I like the solution they mention here

我喜欢他们在这里提到的解决方案

INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);