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

INSERT结合SELECT DISTINCT插入后查询数据重复,求助解决方法

问题解决思路

核心排查方向

大概率是你重复执行了多次INSERT语句——因为theater表没设置主键或唯一约束,每次执行都会插入3条记录,12次重复执行就会导致每个影院出现12次。

快速修复步骤

  1. 先清空现有重复数据(操作前确认表内无需要保留的有效数据):
TRUNCATE TABLE theater;
  1. 仅执行一次你的插入语句:
insert into theater(`name`, email, address, phone)
select distinct theater, theater_email, theater_address, theater_phone
from denormalized_tickets;
  1. 再次查询验证:
select * from theater;

长效预防方案

为避免后续误操作再次插入重复数据,给theater表添加唯一约束,比如基于影院的核心标识字段(名称+地址+电话的组合):

ALTER TABLE theater ADD UNIQUE KEY unique_theater_identity (name, address, phone);

这样以后如果重复执行INSERT语句,数据库会直接抛出唯一约束冲突的错误,不会插入重复记录。

额外排查点(若上述方法无效)

检查SELECT DISTINCT的结果是否存在隐形差异(比如空格、不可见字符),看起来内容相同但实际存储值不同。可以用长度校验语句排查:

SELECT 
  theater, LENGTH(theater) AS theater_length,
  theater_email, LENGTH(theater_email) AS email_length,
  theater_address, LENGTH(theater_address) AS address_length,
  theater_phone, LENGTH(theater_phone) AS phone_length
FROM denormalized_tickets
GROUP BY theater, theater_email, theater_address, theater_phone;

如果发现同一影院的字段长度不一致,说明有隐形字符,插入时先清理:

insert into theater(`name`, email, address, phone)
select distinct 
  TRIM(theater),
  TRIM(theater_email),
  TRIM(theater_address),
  TRIM(theater_phone)
from denormalized_tickets;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:33:53