按两列查找并删除重复行

Find and remove duplicate rows by two columns(按两列查找并删除重复行)
本文介绍了按两列查找并删除重复行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了所有相关的重复问题/答案,我发现这是最相关的答案:

I read all the relevant duplicated questions/answers and I found this to be the most relevant answer:

INSERT IGNORE INTO temp(MAILING_ID,REPORT_ID) 
SELECT DISTINCT MAILING_ID,REPORT_IDFROM table_1
;

问题是我想删除 col1 和 col2 的重复项,但还想将 table_1 的所有其他字段包含到插入中.

The problem is that I want to remove duplicates by col1 and col2, but also want to include to the insert all the other fields of table_1.

我尝试以这种方式添加所有相关列:

I tried to add all the relevant columns this way:

INSERT IGNORE INTO temp(M_ID,MAILING_ID,REPORT_ID,
MAILING_NAME,VISIBILITY,EXPORTED) SELECT DISTINCT  
M_ID,MAILING_ID,REPORT_ID,MAILING_NAME,VISIBILITY,
EXPORTED FROM table_1
;


M_ID(int,primary),MAILING_ID(int),REPORT_ID(int),
MAILING_NAME(varchar),VISIBILITY(varchar),EXPORTED(int)

但它会将所有行插入到 temp 中(包括重复行)

But it inserted all rows into temp (including duplicates)

推荐答案

删除多列重复行最好的方法是最简单的:

The best way to delete duplicate rows by multiple columns is the simplest one:

添加唯一索引:

ALTER IGNORE TABLE your_table ADD UNIQUE (field1,field2,field3);

上面的 IGNORE 确保只保留第一个找到的行,其余的被丢弃.

The IGNORE above makes sure that only the first found row is kept, the rest discarded.

(如果您需要将来重复和/或知道它们不会再次发生,则可以删除该索引).

(You can then drop that index if you need future duplicates and/or know they won't happen again).

这篇关于按两列查找并删除重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)