使用辅助字段排序,开始和结束

时间:2019-01-29 13:04:05

标签: postgresql

在PostgreSQL中,什么是以通用方式使用开始和结束字段对记录进行排序的最佳方法,而无需在查询中包括第一条记录(where start_id=3)?

示例表:

+-------+----------+--------+--------+
| FK_ID | START_ID | END_ID | STRING |
+-------+----------+--------+--------+
|    77 |        1 |      9 | E      |
|    82 |        5 |      2 | A      |
|    77 |        7 |      1 | I      |
|    77 |        3 |      7 | W      |
|    82 |        9 |      5 | Q      |
|    77 |        9 |      5 | X      |
|    82 |        2 |      7 | G      |
+-------+----------+--------+--------+

排序where FK_ID = 77

+----+---+---+---+
| 77 | 3 | 7 | W |
| 77 | 7 | 1 | I |
| 77 | 1 | 9 | E |
| 77 | 9 | 5 | X |
+----+---+---+---+

排序where FK_ID = 82

+----+---+---+---+
| 82 | 9 | 5 | Q |
| 82 | 5 | 2 | A |
| 82 | 2 | 7 | G |
+----+---+---+---+

结果查询顺序:

+-------+----------+
| FK_ID | SEQUENCE |
+-------+----------+
|    82 | QAG      |
|    77 | WIEX     |
+-------+----------+

1 个答案:

答案 0 :(得分:1)

我认为这不是最有效的方法,但是您可以尝试使用递归CTE

WITH RECURSIVE path AS (
  SELECT * FROM myTable AS t1 WHERE NOT EXISTS(
    SELECT 1 FROM myTable AS t2 WHERE t1.fk_id = t2.fk_id AND t2.end_id = t1.start_id
  ) ORDER BY start_id LIMIT 1
  UNION ALL
  SELECT myTable.* FROM myTable JOIN path ON path.end_id = myTable.start_id
)
SELECT fk_id,array_to_string(array_agg(string)) FROM path GROUP BY fk_id