没有重复的自我加入
Self Join without duplicates
我有一个 table 表示 public 交通服务站点之间的可能连接。它看起来像这样:
trip_id | station_id | sequence
--------+------------+---------
1 | A | 1
1 | B | 2
1 | C | 3
2 | C | 1
2 | B | 2
2 | A | 3
现在我想 select 两个站之间所有可能的连接都没有重复,我。 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
最简单的方法是对您的代码进行变体:
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
我有一个 table 表示 public 交通服务站点之间的可能连接。它看起来像这样:
trip_id | station_id | sequence
--------+------------+---------
1 | A | 1
1 | B | 2
1 | C | 3
2 | C | 1
2 | B | 2
2 | A | 3
现在我想 select 两个站之间所有可能的连接都没有重复,我。 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
最简单的方法是对您的代码进行变体:
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