我正在尝试为下表编写分层查询,但无法以我需要的格式获取数据。
以下是表格中的数据:
+---------+-----------+-------------+ | ITEM_ID | FATHER_ID | DESCRIPTION | +---------+-----------+-------------+ | 1019 | 1018 | Level 4 | | 1018 | 1010 | Level 3 | | 1010 | 2 | Level 2 | | 2 | 0 | Level 1 | +---------+-----------+-------------+
这是我在google搜索后想出的查询:
SELECT
SYS_CONNECT_BY_PATH(DESCRIPTION, '\') AS "Path"
FROM
STRUCTURE
START WITH ITEM_ID = 1019
CONNECT BY PRIOR FATHER_ID = ITEM_ID
我得到的输出是:
+---------------------------+ | \Level 4 | | \Level 4\Level 3 | | \Level 4\Level 3\Level 2 | | \Level 4\Level 3\Level 1 | | \Level 4\Level 3\Level 1\ | +---------------------------+
但是如何获得这样的东西(只有一行):
\Level 1\Level 2\Level 3\Level 4
我的查询中缺少什么?
答案 0 :(得分:3)
您需要了解关卡的根目录,并根据评论过滤条建议您使用item_id
。你也颠倒了connect by
语句。您对问题的正确查询是:
SELECT SYS_CONNECT_BY_PATH(description, '\') AS Path
FROM STRUCTURE
WHERE ITEM_ID = 1019
CONNECT BY PRIOR ITEM_ID = FATHER_ID
START WITH FATHER_ID = 0;
但是如果你不知道你关卡的最后一项就是这样:
SELECT SYS_CONNECT_BY_PATH(description, '\') AS Path
FROM STRUCTURE
WHERE ITEM_ID = (select max(item_id) from STRUCTURE)
CONNECT BY PRIOR ITEM_ID = FATHER_ID
START WITH FATHER_ID = 0;
但请注意,第二个查询仅适用于有序的模型,最后一个级别是最后一个。
上查看