SQL:duplicate key value violates unique constraint

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-1 23:23   15   0

错误描述:

### Error updating database.  Cause: com.kingbase8.util.KSQLException: ERROR: duplicate key value violates unique constraint "LEAD_GROUP_PKEY"
  Detail: Key (id)=(1059) already exists.
### The error may involve com.taiji.dao.LeadGroupMapper.insert-Inline
### The error occurred while setting parameters
### SQL: insert into lead_group (group_name, unit_type,unit_id, create_time, code,        header, head_post, head_tel,contact, contact_post, contact_tel, company, company_post, company_tel) values (?, ?,?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?)
### Cause: com.kingbase8.util.KSQLException: ERROR: duplicate key value violates unique constraint "LEAD_GROUP_PKEY"
  Detail: Key (id)=(1059) already exists.
; ]; ERROR: duplicate key value violates unique constraint "LEAD_GROUP_PKEY"
  Detail: Key (id)=(1059) already exists.

原因:

出现这个问题的原因是重复的键值违反了唯一性约束,前面的值已经远大于后边的值,serial key其实是由sequence实现的,当你手动给serial列赋值的时候,sequence是不会自增量变化的,所以最好不要对serial手动赋值。

1.查询这张表的id的自增序列是多少:

//lead_group为表明 id为要查询自增主键
select nextval('lead_group_id_seq');  

2.查看这张表中已经存在的id的最大值是多少。直接在数据库连接工具中输入sql查询

select max(id) from lead_group;

解决方案:

如上图所示:这张表的id的最大值大于 id的自增序列的值。那就证明添加的时候会出现id被占用,而导致id违反唯一性约束的问题。我们只需要重新给id的自增序列赋值,赋一个大于现在表中id的最大值就可以了。

select setval('lead_group_id_seq', (select max(id) from lead_group) + 100)

在重新查询一下,id的自增序列的值是多少,如果和上一步我们设置的值一样的话,就没有问题了。

select nextval('lead_group_id_seq');

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP