MySQL在子查询中选择distinct与exists

时间:2014-02-08 00:19:33

标签: mysql sql

我有一个大约500k行的表,我想删除重复项。首先,我运行select distinct来查看唯一行的计数:

select distinct f1, f2, f3, f4 from my_table;

它返回了我大约300k行。

我想在另一个表中插入唯一的行,所以我运行下一个查询:

insert into table_unique 
    (select * from table where exists 
        (select distinct f1, f2, f3, f4 from my_table)
    )

但是这个查询会向我插入所有行,而不仅仅是唯一行。看起来select distinct在子查询中有点奇怪。

有人能解释一下这种行为吗?

非常感谢。

2 个答案:

答案 0 :(得分:0)

您的Select distinct查询确实会返回每行的一个副本。

但是,您的select * from table where exists会返回与这些不同行匹配的所有记录,从而返回所有副本。

答案 1 :(得分:0)

' table_unique'只包含您与'my_table'?相区的列 如果您只想插入唯一值,则不需要2个嵌套的select语句:

insert into table_unique     
select distinct f1, f2, f3, f4 from my_table

如果有更多列,您必须告诉SQL服务器如何转换数据 - 指定聚合函数或MAX / MIN等等。

在这种情况下,应在select语句

之后添加GROUP BY f1, f2, f3, f4