考虑下表结构和数据
CREATE TABLE Distance(
source VARCHAR(20),
destination VARCHAR(20),
distance INTEGER
);
Select * from Distance;
source destination distance
======= =========== ======
Chennai Mumbai 500
Mumbai Chennai 500
Mumbai Bangalore 500
Bangalore Mumbai 500
Goa Mumbai 100
Mumbai Goa 100
Kolkata Goa 1000
如果重复,我需要输出有 2 个城市的单个记录,即以下 2 个中的任何一个记录都可以。
Chennai Mumbai 500
Mumbai Chennai 500
Expected o/p:
source destination distance
======= =========== ======
Chennai Mumbai 500
Mumbai Bangalore 500
Goa Mumbai 100
Kolkata Goa 1000
最佳答案
这是使用 least()
和 greatest()
的一种方法:
select least(source, destination), greatest(source, destination), max(distance)
from distance
group by least(source, destination), greatest(source, destination);
这样做的缺点是您可能会返回不在表中的行。例如,如果您有一行包含“Mumbai/Chennai/500”,那么此查询将返回“Chennai/Mumbai/500”——并且该行不在原始表中。
因此,另一种方法是:
select source, destination, distance
from distance
where source < destination
union all
select destination, source, distance
from distance d
where source > destination and
not exists (select 1
from distance d2
where d2.source = d.destination and d2.destination = d.source
);
此版本也与 ANSI 兼容,应该适用于所有数据库。
关于mysql - SQL获取两列组合的不同记录(不考虑顺序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33873643/