使用先验连接显示数据的父级?
show the parent of a data using connect by prior?
我有这个 table 我有
parentitem | childitem ---table name
dinner | steak
dinner | wine
dinner | mashed potato
dinner | coffee
coffee | sugar
coffee | water
dinner | cake
cake | liquid syrup
cake | egg
我想使用 connect 检索 'dinner' 的所有子项,之前我使用了 ff 代码
Select Level, LPAD('->',2*(LEVEL-1))||CHILDITEM From table
Start With parentitem = 'dinner' Connect By Prior childitem =
parentitem
但它不包括 'dinner' 的父项,但它可以正确生成晚餐的所有子项,顺便说一句,我的朋友提示我使用 union。我正在使用甲骨文。
所以我的预期结果是
LEVEL | CHILDITEM
0 | dinner
1 | steak
1 | wine
1 | mashed potato
1 | coffee
2 | sugar
2 | water
1 | cake
2 | liquid syrup
2 | egg
问题是您的数据中没有 "dinner" 作为子项。
如果你这样做了,这将是一件简单的事情 START WITH childitem='dinner'
。
例如,
SELECT LEVEL,
LPAD ('->', 2 * (LEVEL - 1)) || childitem
FROM t
START WITH childitem = 'dinner'
CONNECT BY PRIOR childitem = parentitem
由于您的数据,如果您希望 "dinner" 列为子项,您需要在查询中创建一个不存在的行。 UNION ALL
是一个很好的方法。例如,
SELECT 0 AS "LEVEL",
'dinner' childitem
FROM DUAL
UNION ALL
SELECT LEVEL,
LPAD ('->', 2 * (LEVEL - 1)) || childitem
FROM t
START WITH parentitem = 'dinner'
CONNECT BY PRIOR childitem = parentitem
另一种方法是使用 UNION ALL
创建源数据中缺失的行。例如,
SELECT LEVEL,
LPAD ('->', 2 * (LEVEL - 1)) || childitem
FROM (SELECT NULL parentitem,
'dinner' childitem
FROM DUAL
UNION ALL
SELECT parentitem,
childitem
FROM t) t
START WITH childitem = 'dinner'
CONNECT BY PRIOR childitem = parentitem
我有这个 table 我有
parentitem | childitem ---table name
dinner | steak
dinner | wine
dinner | mashed potato
dinner | coffee
coffee | sugar
coffee | water
dinner | cake
cake | liquid syrup
cake | egg
我想使用 connect 检索 'dinner' 的所有子项,之前我使用了 ff 代码
Select Level, LPAD('->',2*(LEVEL-1))||CHILDITEM From table
Start With parentitem = 'dinner' Connect By Prior childitem =
parentitem
但它不包括 'dinner' 的父项,但它可以正确生成晚餐的所有子项,顺便说一句,我的朋友提示我使用 union。我正在使用甲骨文。
所以我的预期结果是
LEVEL | CHILDITEM
0 | dinner
1 | steak
1 | wine
1 | mashed potato
1 | coffee
2 | sugar
2 | water
1 | cake
2 | liquid syrup
2 | egg
问题是您的数据中没有 "dinner" 作为子项。
如果你这样做了,这将是一件简单的事情 START WITH childitem='dinner'
。
例如,
SELECT LEVEL,
LPAD ('->', 2 * (LEVEL - 1)) || childitem
FROM t
START WITH childitem = 'dinner'
CONNECT BY PRIOR childitem = parentitem
由于您的数据,如果您希望 "dinner" 列为子项,您需要在查询中创建一个不存在的行。 UNION ALL
是一个很好的方法。例如,
SELECT 0 AS "LEVEL",
'dinner' childitem
FROM DUAL
UNION ALL
SELECT LEVEL,
LPAD ('->', 2 * (LEVEL - 1)) || childitem
FROM t
START WITH parentitem = 'dinner'
CONNECT BY PRIOR childitem = parentitem
另一种方法是使用 UNION ALL
创建源数据中缺失的行。例如,
SELECT LEVEL,
LPAD ('->', 2 * (LEVEL - 1)) || childitem
FROM (SELECT NULL parentitem,
'dinner' childitem
FROM DUAL
UNION ALL
SELECT parentitem,
childitem
FROM t) t
START WITH childitem = 'dinner'
CONNECT BY PRIOR childitem = parentitem