Mysql 使用sql删除同表中重复数据并加唯一索引

数据库   发布日期:2025年04月30日   浏览次数:224

同一张表中,假设以两个字段做唯一业务,这两个字段分别为key1,key2,

则以这两个字段为唯一

  1. DELETE tablename FROM
  2. tablename ,
  3. (
  4. SELECT
  5. min(id) id,
  6. key1, key2
  7. FROM
  8. tablename
  9. GROUP BY
  10. key1, key2
  11. HAVING
  12. count(*) > 1
  13. ) t2
  14. WHERE
  15. tablename .key1=t2.key1
  16. AND tablename .key2=t2.key2
  17. AND tablename .id > t2.id;

 增加唯一索引

  1. ALTER TABLE t_procurement_order_instock add unique index uniq_t_procurement_order_instock(`t_procurement_order_instock_id`);  

  1. ALTER TABLE tablename
  2. DROP INDEX ix_instock_date_warehouse_g_f_lu_standard_item,
  3. ADD INDEX idx_f_lu_standard_item_warehouse_g_item_status_instock_date(`f_lu_standard_item`,`warehouse_g`,`item_status`,`instock_date`);

  4. ALTER TABLE tablename
  5. DROP INDEX IND_PAY_ORDER_1;                                                                    
  6. ALTER IGNORE TABLE PAY_ORDER ADD UNIQUE INDEX IND_PAY_ORDER_1(ORDER_ID);               ORDER_ID设为唯一索引(IND_PAY_ORDER_1)删除重复数据

  

以上就是Mysql 使用sql删除同表中重复数据并加唯一索引的详细内容,更多关于Mysql 使用sql删除同表中重复数据并加唯一索引的资料请关注九品源码其它相关文章!