mysql数据库中删除重复的记录只保留一条

特别提醒:删除数据一定要谨慎
  1. 表名:dw_invested_company_qmp 两列数据:deal_name, invest_time(除了id)

  2. 查询出所有重复记录中id最小的一条记录

SELECT COUNT(*) as num,deal_name,invest_time,min(id) as id 
FROM dw_invested_company_qmp 
GROUP BY deal_name,invest_time having num > 1;
  1. 取出上一步中所有的id
SELECT e.id FROM 
(SELECT COUNT(*) as num,deal_name,invest_time,min(id) as id FROM dw_invested_company_qmp GROUP BY deal_name,invest_time) as e 
WHERE e.num>1;
  1. 根据上一步中得到的id进行删除
DELETE FROM dw_invested_company_qmp
WHERE id IN 
(SELECT e.id FROM (SELECT COUNT(*) as num,deal_name,invest_time,min(id) as id FROM dw_invested_company_qmp GROUP BY deal_name,invest_time) as e WHERE e.num>1);
说明:如果数据库中重复的记录大于2, 可重复上述步骤删除
删除数据一定要谨慎 !否则就得跑路了!

你可能感兴趣的:(数据库交互模块)