PostgreSQL 9.2 - 条件插入失败,重复密钥违规

时间:2016-01-22 12:03:06

标签: sql duplicates sql-insert 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是pkey)

1 个答案:

答案 0 :(得分: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