mysql - 单表跨列唯一值的SQL查询
问题描述
我有一个包含两列和数据的表格,如下所示 -
+---------+---------+
| Column1 | Column2 |
+---------+---------+
| A | B |
+---------+---------+
| C | D |
+---------+---------+
| B | A |
+---------+---------+
| E | F |
+---------+---------+
| F | E |
+---------+---------+
我的查询输出应返回以下数据 -
+---------+---------+
| Column1 | Column2 |
+---------+---------+
| A | B |
+---------+---------+
| C | D |
+---------+---------+
| E | F |
+---------+---------+
如果我们有两行row1
和row2
whererow1.column1=row2.column2
和row1.column2=row2.column1
,则输出应该包含两行中的任何一个row1
或row2
。
你能帮我解决这个问题吗?
解决方案
我想你想要:
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;
请注意,在某些情况下,这可能会返回对在原始数据中的顺序不同。
推荐阅读
- javascript - 从客户端 PC 下载 blob 文件时出现未经授权的访问错误
- python - Python 错误没有找到带有标签的句柄以使用 matplotlib 放入图例
- html - React Image Container Div 切断
- python - 如何使用 wait_for
- java - 无法使用 java swing 从类路径渲染图像?
- android - android撰写文本字段如何在触摸外部时关闭键盘
- c - 如何更新现有应用的 Lua 库?
- node.js - 有没有办法将音频和视频流合并到一个文件中并将其通过管道传输到 res
- r - 获取R中每对直接连接节点之间的相互连接节点列表
- java - snakeyaml 如何将对象列表写回 yaml 文件,而不以“!!”开头的行