我有一张这样的桌子:
-------------------------------------------------
| id | description | parent_id | cost
--------------------------------------------------
| 1 | Radiology | NULL | 0.00
| 2 | Lab Tests | NULL | 0.00
| 3 | Normal Radiology | 1 | 0.00
| 4 | Resonance | 1 | 100.00
| 1100 | Cerebral Resonance| 4 | 200.00
| 1900 | Blood Tests | 2 | 10.00
| 2044 | Calcium | 2 | 50.00
---------------------------------------------------
我需要生成这种输出:
Radiology
-->Normal Radiology
-->Resonance
-->Cerebral Resonance with contrast
Lab Test
--> Blood Test
--> Calcium
我正在研究 PostgreSQL。我一直在尝试使用递归 CTE,但无法生成我喜欢的内容:
WITH RECURSIVE hierarchy AS (
SELECT id, CAST(description AS TEXT) AS parent_list
FROM orders
WHERE parent_id is null
UNION
SELECT c.id,
CAST(c2.parent_list || ' --> ' || c.description as text) as parent_list
FROM orders c
INNER JOIN hierarchy c2 ON c.parent_id = c2.id )
SELECT id, parent_list
FROM hierarchy
GROUP BY id, parent_list
ORDER BY parent_list;
该递归 CTE 会产生以下不受欢迎的输出:
Radiology
Radiology--> Normal Radiology
Radiology--> Resonance
Radiology--> Resonance --> Cerebral Resonance with contrast
Lab Test
Lab Test --> Blood Test
Lab Test --> Calcium
我该怎么做?