问题:insert 出现duplicate key value violates unique constraint错误


scanner=# INSERT INTO task_ip (task_id,target_ip,hostname,time_start) VALUES (1111,'10.10.10.10','ubp','2008-09-09');
ERROR: duplicate key value violates unique constraint "task_ip_pkey"
DETAIL: Key (id)=(659) already exists.

原因:

出现这个问题的原因是大批量插入数据导致task_ip表和task_ip_id_seq不一致造成的,从下面的两个sql语句可以看出,前面的值已经远大于后边的值,

scanner=# select max(id) from task_ip;
max
--------
152634
(1 row)

scanner=# SELECT nextval('task_ip_id_seq');
nextval
---------
661
(1 row)

scanner=# select setval('task_ip_id_seq', (select max(id) from task_ip) + 1)
;
setval
--------
152635
(1 row)

scanner=# SELECT func_task_add_host(15270,'10.10.10.10','10.101.01.10','2010-01-01','');
func_task_add_host
--------------------
152636
(1 row)