sql - 自加入无重复
问题描述
我有一张表格,代表公共交通服务站之间可能的连接。它看起来像这样:
trip_id | station_id | sequence
--------+------------+---------
1 | A | 1
1 | B | 2
1 | C | 3
2 | C | 1
2 | B | 2
2 | A | 3
现在我想选择两个站之间所有可能的连接而不重复,即我只需要连接 A->B 而不是 B->A。
我想出了这个加入,但不幸的是有重复:
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
推荐阅读
- go - go - 如何在go golang中的特定内存地址声明一个指针并在那里存储一个值
- javascript - 如何在不使用 DOM 函数的情况下将 Uint8ClampedArray 转换为图像?
- django - Django嵌套if语句给了我一个奇怪的错误
- java - 如何在单个语句中运行多个查询
- ng-bootstrap - 从 ngbDropdownToggle 中删除小箭头
- javascript - 将报价添加到没有报价的 json 文件
- java - 独立罐空手道问题
- python - 无法确定为什么 MNE raw.plot 返回“ValueError:bottom cannot be >= top”
- java - 有没有简单的方法在不使用比较器的情况下对数组进行排序后保留原始索引?
- pandas - 如何将字典的文本文件读取到数据框?