SheepDog1998

博客园 首页 新随笔 联系 订阅 管理

起因是在线上环境遇到了:

2026-01-13 09:00:26.838 [EqTask-17] ERROR com.push.sys.services.impl.RealEarthquakeServiceImpl.lambda$retryRunnable$5:379 - 执行异常,重试次数:1,异常信息:
### Error updating database.  Cause: org.postgresql.util.PSQLException: 错误: 重复键违反唯一约束"t_100_influence_field_pkey"
  Detail: 键值"(id)=(961)" 已经存在
### The error may exist in com/push/sys/dao/InfluenceFieldResultMapper.java (best guess)
### The error may involve com.push.sys.dao.InfluenceFieldResultMapper.insert-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO t_100_influence_field  ( geom, catalogid, ms, liedu, level, lon, lat, lon1, lat1, name, time, angle, majorhaxis, minorhaxis, l, yxctype,  shape_area, material,  create_time, field_name, field_group_id, field_type )  VALUES  ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,  ?, ?,  ?, ?, ?, ? )
### Cause: org.postgresql.util.PSQLException: 错误: 重复键违反唯一约束"t_100_influence_field_pkey"
  Detail: 键值"(id)=(961)" 已经存在
; 错误: 重复键违反唯一约束"t_100_influence_field_pkey"
  Detail: 键值"(id)=(961)" 已经存在; nested exception is org.postgresql.util.PSQLException: 错误: 重复键违反唯一约束"t_100_influence_field_pkey"
  Detail: 键值"(id)=(961)" 已经存在

 

根本原因是:PostgreSQL 的序列(Sequence)与表中的实际数据不同步

解决方案:

-- 查询表 t_100_influence_field 的 id 字段使用了哪个序列
SELECT pg_get_serial_sequence('t_100_influence_field', 'id');

-- 查看序列当前的 last_value
SELECT last_value FROM t_100_influence_field_id_seq;

-- 查看当前最大 id(如果没有数据,结果为 NULL)
SELECT MAX(id) FROM t_100_influence_field;

-- 查看当前序列下一个值是多少
SELECT 
    last_value,
    increment_by,
    -- 计算下一个值
    last_value + increment_by AS next_value_would_be
FROM 
    pg_sequences 
WHERE 
    sequencename = 't_100_influence_field_id_seq';

-- 核心修复语句:
-- 将序列 t_100_influence_field_id_seq 的当前值,设置为表中 id 字段最大值 + 1
SELECT setval('t_100_influence_field_id_seq', (SELECT COALESCE(MAX(id), 0) + 1 FROM t_100_influence_field));

 

posted on 2026-01-13 10:05  SheepDog1998  阅读(1)  评论(0)    收藏  举报