0

我有一个包含一些重复记录的表。我想让记录变得独一无二。我创建了一个新表(比如目的地),并在其中指定了一个唯一列。如何从 table1(源)复制记录,这样,如果记录插入到目标表中,它就不会再次插入它。

4

3 回答 3

1

您可以使用“ select into ”构造并选择仅插入不同的行,如下所示:

insert into table_without_dupes (column0, column1) select distinct column0, column1 from table_with_dupes

如果您有使行不同的自动增量或其他列,您可以将它们排除在插入之外并选择语句的一部分。

编辑:

如果要按单个列检测重复项,可以使用 group by:

insert into table_without_dupes (column0, column1) select column0, column1 from table_with_dupes group by column0

MySQL 将允许您在 select 中引用非聚合列,但请记住文档说“服务器可以从每个组中自由选择任何值”,如果您想选择组中的一个特定行,您可能会找到这个示例有用。

于 2012-07-20T08:56:17.670 回答
1

通用方法

insert into destination(col1,col2)
select DISTINCT col1,col2 from source as s where not exists
(select * from destination as d where d.col1=s.col1)

已编辑

   insert into destination(col1,col2)
   SELECT distinct col1,col2 from source

已编辑(假设 col3 是重复的,并且您只需要它的一个副本。)

insert into destination(col1,col2,col3,....,colN)
SELECT col1,col2,col3,...,colN from source as s1 inner join
(
select col1,col2,max(col3) as  col3 
from source 
group by col1,col2
) as s2 on t1.col1=t2.col1 and t1.col2=t2.col2 and t1.col3=t2.col3
于 2012-07-20T08:57:27.243 回答
0
insert into <dest_table_name>
select distinct * from <source_table_name>;
于 2012-07-20T09:01:11.993 回答