PostgreSQL 数据库 - 仅在记录不存在时插入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13902337/
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
PostgreSQL database - only insert if the record doesn't exist
提问by Jimmy
Possible Duplicate:
Cannot SELECT from UPDATE RETURNING clause in postgres
I am using a postgreSQL database which has a "company" table and a "country" table which each have a uniqueID.
我正在使用一个 postgreSQL 数据库,它有一个“公司”表和一个“国家”表,每个表都有一个 uniqueID。
I want a setup where if I try to add a company to the database, it only adds the company to the database with a new unique ID if it doesn't already exist.
我想要一个设置,如果我尝试将公司添加到数据库中,它只会将公司添加到数据库中,如果它不存在,则使用新的唯一 ID。
If anyone is able to shed some light on this I would really appreciate it,
如果有人能够对此有所了解,我将不胜感激,
James
詹姆士
回答by a_horse_with_no_name
insert into company (unique_id, company_name)
select 42, 'New Company Name'
from company
where not exists (select 1 from company where unique_id = 42);
See also here for a more general solution: Insert, on duplicate update in PostgreSQL?
另请参阅此处了解更通用的解决方案:插入,在 PostgreSQL 中重复更新?