【问题标题】:MySQL select distinct in subquery with existsMySQL在子查询中选择不同的存在
【发布时间】:2014-02-08 00:19:33
【问题描述】:

我有一个大约有 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 在子查询中有点奇怪。

谁能解释一下这种行为?

非常感谢。

【问题讨论】:

  • 子查询中的select distinct 没有意义。 in 基本上已经删除了重复项。

标签: mysql sql


【解决方案1】:

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

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

【讨论】:

  • 谢谢,我现在明白了。所以它看起来像我做我需要的唯一方法是使用select in而不是existsgroup by而不是distinct
【解决方案2】:

“table_unique”是否只有与“my_table”不同的列? 如果您只想插入唯一值,则不需要 2 个嵌套的 select 语句:

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

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

在这种情况下GROUP BY f1, f2, f3, f4应该在select语句之后添加

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多