如何编写查询来确定 'AB' 和 'BA' 是否相同?

How to write a query to determine if 'AB' and 'BA' are the same?

我有点卡在这里。我正在尝试为每条路线分配一个唯一的路线 ID,无论是单程还是往返。

例如我有两列,起点和终点:

换句话说,我如何编写查询来标记 DC 到 NYC 和 NYC 到 DC 基本相同的路线 (routeA) 而不是不同的路线。在这种情况下,我只关心城市对,而不关心行进方向。

PS:我正在使用 MySQL

谢谢!

您可以通过执行以下操作来枚举这些对:

select least(origin, destination) as city1,
       greatest(origin, destination) as city2,
       (@route := @route + 1) as route_number
from t cross join
     (select @route := 0) params
group by least(origin, destination), greatest(origin, destination);

或者,另一种方法是创建一个路由名称:

select t.*,
       concat_ws(':', least(origin, destination) as city1,
                 greatest(origin, destination) 
                ) as route_name
from t;