2016-01-22 68 views
0

以下条件插入仅在项目已存在时才起作用! (不会试图插入)。PostgreSQL 9.2 - 条件插入失败,重复键冲突

如果该项不存在,我会得到重复密钥违规(重复密钥违反唯一约束)! 使用PostgreSQL 9.2

INSERT INTO mytable (mytable_handle, title, description) 
select '1234/9876', 'Title here', 'description here' 
from mytable where not exists 
(select 1 from mytable where mytable_handle = '1234/9876') 

(mytable_handle是p键)

+0

问:'mytable_handle'是一个*字符*列?作为主键? – joop

+0

其实我们在'1234/9876'之类的字段中使用字符串。刚刚更新了这个问题。 – pkaramol

回答

0

这个查询:

select '1234', 'Title here', 'description here' 
from mytable where not exists 
(select 1 from mytable where mytable_handle = '1234'); 

将返回元组'1234', 'Title here', 'description here'一次已经存在于表中的每一行,如果mytable_handle值不存在。运行在自己的select,你会为自己

看到你想要的:

select '1234', 'Title here', 'description here' 
where not exists 
(select 1 from mytable where mytable_handle = '1234'); 

SQLFiddle例如:http://sqlfiddle.com/#!15/b331f/1