【发布时间】: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相同)
【问题讨论】:
one table a= {el1, el2}
where el1 is 1..10, el2 is {5..15}.
表中的记录就像[el1, el2]
还有一些记录[el2, el1],即它们是相同的,只是在不同的列中。
获取唯一 el1、el2 元素的最佳方法是什么? (记录1,2与2,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)
【讨论】:
擦洗数据(拖地...):
SELECT el1, el2
FROM YourTable
UNION
SELECT el2 AS el1, el1 AS el2
FROM YourTable;
为了防止数据损坏再次发生(...修复泄漏):
ALTER TABLE YourTable ADD
CHECK ( el1 < el2 );
【讨论】: