Oracle 11g - 选择查询帮助。
表" data_table"有如下三个字段,并保持子父关系,如下所示 -
user_code -> description -> parent_code
A -> Root ID -> B
B -> Level1 -> C
C -> Level2 -> D
D -> Level3 -> E
E -> Level4 -> F
要求是将此层次结构发布在一行中,如下所示。
**
Root ID -> Level1 -> Level2 -> Level3-> Level4
A -> B -> C -> D -> E **
我有什么选择?请帮忙..
现在我使用下面的查询,但看起来并不好。
SELECT e.user_code user_code,
d.description user_description,
e.parent_code level1,
a.parent_code level2 ,
b.parent_code level3 ,
c.parent_code level4
FROM data_table e,
data_table a,
data_table b,
data_table c,
data_table d
WHERE e.user_code = d.user_code
AND b.user_code = a.parent_code
AND c.user_code = b.parent_code
AND e.parent_code = a.user_code
答案 0 :(得分:1)
您必须使用通过user_code和parent_code连接父级和子级的层次结构查询。像这样:
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
SYS_CONNECT_BY_PATH显示路径,但如果您想要将整个路径放在一行中,则需要获取MAX。
您可以阅读有关等级查询here
的更多信息答案 1 :(得分:0)
如果您知道有固定数量的关卡,则可以执行以下操作:
with sample_data as (select 'A' user_code, 'Root ID' description, 'B' parent_code from dual union all
select 'B' user_code, 'Level 1' description, 'C' parent_code from dual union all
select 'C' user_code, 'Level 2' description, 'D' parent_code from dual union all
select 'D' user_code, 'Level 3' description, 'E' parent_code from dual union all
select 'E' user_code, 'Level 4' description, 'F' parent_code from dual union all
select 'G' user_code, 'Root ID' description, 'H' parent_code from dual union all
select 'H' user_code, 'Level 1' description, 'I' parent_code from dual union all
select 'I' user_code, 'Level 2' description, 'J' parent_code from dual union all
select 'J' user_code, 'Level 3' description, 'K' parent_code from dual),
res as (select sd.user_code,
sd.description,
connect_by_root(sd.user_code) top_node
from sample_data sd
connect by sd.user_code = prior sd.parent_code
start with sd.description = 'Root ID')
select root_id,
level1,
level2,
level3,
level4
from res
pivot (max(user_code) for description in ('Root ID' as root_id,
'Level 1' as level1,
'Level 2' as level2,
'Level 3' as level3,
'Level 4' as level4))
order by top_node;
ROOT_ID LEVEL1 LEVEL2 LEVEL3 LEVEL4
------- ------ ------ ------ ------
A B C D E
G H I J
如果级别数量未知,那么您将不得不调查动态数据透视 - 如果您搜索Google,有很多关于如何进行动态数据透视的示例。