【问题标题】:How to find duplicated data group in Oracle如何在Oracle中查找重复的数据组
【发布时间】:2020-10-09 10:30:06
【问题描述】:

假设我有一个像这样的简单表格:

  f1   |   f2
--------------
   a   |   b
   b   |   a
   a   |   c
   c   |   a
   a   |   d
   d   |   a

f1f2 本质上是相似的,它们之间的关系顺序无关紧要。我的意思是如果我说a与b有关,那么b与a有关

我需要找到重复的关系并删除它们。在此示例中 (a,b) , (a,c) , (a,d) OR (b,a) , (c,a) , (d,a) ,应查找并删除这三个记录集之一。

任何人请给我一个查找重复数据组的查询。

非常感谢

【问题讨论】:

    标签: sql oracle select duplicates


    【解决方案1】:

    您可以使用exists 来展示“镜像”记录:

    select t.*
    from mytable t
    where exists (select 1 from mytable t1 where t1.f1 = t.f2 and t1.f2 = t.f1)
    

    如果您只想要其中一个副本,那么:

    select t.*
    from mytable t
    where 
        t.f1 < t.f2 
        and exists (select 1 from mytable t1 where t1.f1 = t.f2 and t1.f2 = t.f1)
    

    【讨论】:

    • where (t1.f1, t1.f2) = (t.f2, t.f1) 是 oracle 中的无效表达式并导致引发 ORA-00920: invalid relational operator
    • 我尝试了where (t1.f1=t.f2 and t1.f2=t.f1),但不幸的是它导致了mytable中的全部记录
    • @AliAdlavaran:那是因为您表中的所有记录实际上都被其他记录“镜像”了......您真正想要哪个结果?
    • 是的,所有的关系都是镜像的。我只需要(a,b) , (a,c) , (a,d) 3 条记录作为结果
    • @AliAdlavaran:在where 子句中再添加一个条件:where f1 &lt; f2 and exists (select 1 from mytable t1 where t1.f1 = t.f2 and t1.f2 = t.f1)
    【解决方案2】:

    您可以使用EXISTSGREATER THAN 运算符,如下所示:

    SELECT * FROM YOUR_TABLE T
     WHERE EXISTS (
        SELECT 1
          FROM YOUR_TABLE T1
         WHERE T1.F1 = T.F2
           AND T1.F2 = T.F1
    )
    AND T1.F1 > T1.F2;
    

    如果您想删除此类重复记录,请在上述查询中使用DELETE 而不是SELECT *

    【讨论】:

    • 嘿 Tejash,恭喜您获得 oracle 金牌!
    猜你喜欢
    • 2011-12-07
    • 2010-09-08
    • 2014-11-11
    • 2021-06-20
    • 2021-08-04
    • 1970-01-01
    • 2011-12-18
    • 2012-05-04
    • 1970-01-01
    相关资源
    最近更新 更多