首页 > 解决方案 > 单表跨列唯一值的SQL查询

问题描述

我有一个包含两列和数据的表格,如下所示 -

+---------+---------+
| Column1 | Column2 |
+---------+---------+
| A       | B       |
+---------+---------+
| C       | D       |
+---------+---------+
| B       | A       |
+---------+---------+
| E       | F       |
+---------+---------+
| F       | E       |
+---------+---------+

我的查询输出应返回以下数据 -

+---------+---------+
| Column1 | Column2 |
+---------+---------+
| A       | B       |
+---------+---------+
| C       | D       |
+---------+---------+
| E       | F       |
+---------+---------+

如果我们有两行row1row2whererow1.column1=row2.column2row1.column2=row2.column1,则输出应该包含两行中的任何一个row1row2

你能帮我解决这个问题吗?

标签: mysqlsqloracle11g

解决方案


我想你想要:

select col1, col2
from t
where col1 < col2
union all
select col1, col2
from t
where col1 > col2 and
      not exists (select 1 from t t2 where t2.col1 = t.col2 and t2.col2 = t.col1);

您可能还想要:

select distinct least(col1, col2) as col1, greatest(col1, col2) as col2
from t;

请注意,在某些情况下,这可能会返回对在原始数据中的顺序不同。


推荐阅读