2016-01-22 42 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