INSERT结合SELECT DISTINCT插入后查询数据重复,求助解决方法
问题解决思路
核心排查方向
大概率是你重复执行了多次INSERT语句——因为theater表没设置主键或唯一约束,每次执行都会插入3条记录,12次重复执行就会导致每个影院出现12次。
快速修复步骤
- 先清空现有重复数据(操作前确认表内无需要保留的有效数据):
TRUNCATE TABLE theater;
- 仅执行一次你的插入语句:
insert into theater(`name`, email, address, phone) select distinct theater, theater_email, theater_address, theater_phone from denormalized_tickets;
- 再次查询验证:
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
相关产品推荐
相关产品推荐

