You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

插入不重复数据失效求助:event_id重复仍新增行

解决插入数据时event_id重复的问题

你的问题出在distinct仅能去除target_table内部的重复行,但不会校验existing_table中已存在的event_id,所以重复数据还是会被插入。以下是几种可行的解决方法:

方法1:用NOT EXISTS过滤已存在的event_id

修改插入语句,通过子查询排除existing_table中已有的event_id:

insert into existing_table
select distinct 
  event_id
  , event
  , cs.pid as cs_pid
  , context_page_url
  , try_cast(concat(cs.year, "-", cs.month, "-", cs.day) as string) as event_date
  , split_part(cs.context_page_url, '|', 0) as stem
from target_table cs 
where year=2023 
  and not exists (
    select 1 from existing_table et where et.event_id = cs.event_id
  )

方法2:用LEFT JOIN过滤重复行

通过左连接筛选出existing_table中没有匹配的行:

insert into existing_table
select distinct 
  cs.event_id
  , cs.event
  , cs.pid as cs_pid
  , cs.context_page_url
  , try_cast(concat(cs.year, "-", cs.month, "-", cs.day) as string) as event_date
  , split_part(cs.context_page_url, '|', 0) as stem
from target_table cs 
left join existing_table et on cs.event_id = et.event_id
where cs.year=2023 
  and et.event_id is null

额外建议:添加唯一约束

为了从数据库层面彻底防止重复插入,给existing_table的event_id字段添加唯一约束:

PostgreSQL

ALTER TABLE existing_table ADD CONSTRAINT unique_event_id UNIQUE (event_id);

MySQL

ALTER TABLE existing_table ADD UNIQUE INDEX idx_unique_event_id (event_id);

添加约束后,若再尝试插入重复的event_id,数据库会直接抛出错误,不会插入重复行。

内容的提问来源于stack exchange,提问作者DBA_player

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 22:12:11