我有一个表,代表公共交通服务站点之间的可能连接。看起来像这样:
trip_id | station_id | sequence
--------+------------+---------
1 | A | 1
1 | B | 2
1 | C | 3
2 | C | 1
2 | B | 2
2 | A | 3
现在,我想选择两个站点之间所有可能的连接而没有重复,i。 e。我只需要连接A-> B而不是B-> A。
我想出了这个Join,但是不幸的是有重复项:
SELECT DISTINCT c1.station_id, c2.sation_id
FROM connections c1, connections c2
WHERE c1.trip_id = c2.trip_id AND c1.sequence = c2.sequence-1
答案 0 :(得分:1)
最简单的方法是对代码进行修改:
SELECT DISTINCT LEAST(c1.station_id, c2.station_id) as station_id1,
GREATEST(c1.station_id, c2.station_id) as station_id2
FROM connections c1 JOIN
connections c2
c1.trip_id = c2.trip_id AND c1.sequence = c2.sequence - 1