我正在寻找在一行中显示父条目和子条目的最佳方法。 例如:
Table A
ID | PARENT_ID | VALUE
=============================
1 | | A
2 | 1 | B
3 | 2 | C
4 | | D
5 | 4 | E
所以我希望得到以下结果:
ID | PARENT | CHILD | VALUE
=========================================
2 | 1 | 3 | A
5 | 4 | | E
你会如何解决这个问题?
任何帮助他非常感激。
丹尼尔
答案 0 :(得分:3)
您可以通过自我加入轻松完成:
SQL> WITH table_a AS (
2 SELECT 1 ID, NULL parent_id, 'A' VALUE FROM dual
3 UNION ALL SELECT 2, 1, 'B' FROM dual
4 UNION ALL SELECT 3, 2, 'C' FROM dual
5 UNION ALL SELECT 4, NULL, 'D' FROM dual
6 UNION ALL SELECT 5, 4, 'E' FROM dual
7 )
8 SELECT children.id, children.parent_id,
9 grand_children.id, children.value
10 FROM (SELECT ID, parent_id, VALUE
11 FROM table_a
12 WHERE LEVEL = 2
13 CONNECT BY parent_id = PRIOR ID
14 START WITH parent_id IS NULL) children
15 LEFT JOIN table_a grand_children
16 ON children.id = grand_children.parent_id;
ID PARENT_ID ID VALUE
---------- ---------- ---------- -----
2 1 3 B
5 4 E