2

我正在寻找在一行中显示父项和子项的最佳方式。例子:

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

你会如何解决这个问题?

他非常感谢任何帮助。

丹尼尔

4

1 回答 1

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
于 2010-02-03T09:30:41.163 回答