【问题标题】:find unique records within a table查找表中的唯一记录
【发布时间】:2012-03-01 14:09:44
【问题描述】:
one table a= {el1, el2}
where el1 is 1..10, el2 is {5..15}. 

表中的记录就像[el1, el2] 还有一些记录[el2, el1],即它们是相同的,只是在不同的列中。

获取唯一 el1、el2 元素的最佳方法是什么? (记录1,2与2,1相同)

【问题讨论】:

    标签: sql database unique


    【解决方案1】:

    我确信有一个更优雅的解决方案,但现在我想不出它。如果反转列,第一部分会查找无法找到匹配项的行。第二个查找如果您反转列,您可以找到匹配的行 - 并处理每列中具有相同值的 [el1, el2] 对

    select t1.el1, t1.el2
    from @tbl t1
    where not exists (select * from @tbl t2 where t2.el1 = t1.el2 and t2.el2 = t1.el1)
    
    union
    
    select t1.el1, t1.el2
    from @tbl t1
    where exists (select * from @tbl t2 where t2.el1 = t1.el2 and t2.el2 = t1.el1 and t2.el1 <= t1.el1)
    

    【讨论】:

    • 我想出了一个有点不同的解决方案,做了一个联合,即 table1(a,b) table2(a,b) select a,b from t1 where a
    • 那么为什么不发布它以帮助其他人?
    【解决方案2】:

    擦洗数据(拖地...):

    SELECT el1, el2
      FROM YourTable
    UNION
    SELECT el2 AS el1, el1 AS el2
      FROM YourTable;
    

    为了防止数据损坏再次发生(...修复泄漏):

    ALTER TABLE YourTable ADD
        CHECK ( el1 < el2 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多