【问题标题】:hierarchical query on OracleOracle上的分层查询
【发布时间】:2014-07-24 21:11:02
【问题描述】:

我正在尝试在 Oracle 上编写一个涉及两个表的分层查询:

GeoNodes
Name, uuid, lat, lon

GeoParents
parent_uuid, child_uuid

示例数据:

GeoNodes
Name    UUID  lat  lon
test1   123   0    0
test2   124   0    0
test3   125   0    0
test4   126   0    0

GeoParents
parent_uuid   child_uuid
123           124
123           125
124           126

在这个例子中,我有:

  • test2 和 test3 的 test1 父级
  • test4 的 test2 父级

geoparents 表中没有空值。在 geoparents 上,geonodes 的 uuid 列上有两个 FK(一个用于子级,一个用于父级),用于维护两个表之间的数据完整性。

如您所见,父子之间的链接保留在外部表上。 为了让所有人都更加复杂,一些节点有不止一个父节点。

遗憾的是,我不明白将联接放在查询中的哪个位置以使其正常工作。我搜索了示例,但所有示例在数据表中都有父列。

这是提取一些全等数据的唯一查询,但遗憾的是无法获得根记录:

select Lpad(soc || '_' || name,Length(soc || '_' || name) + LEVEL * 3 - 3,'-') 
from geonodes g, geoparents p
where g.uuid = p.child_uuid
start with name = 'myTest'
connect by prior g.uuid = p.PARENT_UUID
order siblings by name;

提前感谢您的帮助。

【问题讨论】:

  • 能否请您发布一些数据示例。
  • 事先连接应该会有所帮助。

标签: sql oracle


【解决方案1】:

首先,构建树:

SELECT child_uuid uuid
FROM   geoparents
CONNECT BY PRIOR child_uuid = parent_uuid
START WITH parent_uuid IS NULL;

然后你就可以加入信息表了:

SELECT *
FROM (SELECT child_uuid uuid
      FROM   geoparents
      CONNECT BY PRIOR child_uuid = parent_uuid
      START WITH parent_uuid IS NULL) tree,
      geonodes
WHERE tree.uuid = geonodes.uuid;

但我认为您不需要有两张桌子。是什么阻止您将 parent_uuid 存储在 geonodes 表中?

【讨论】:

  • parent_uuid = NULL; 在 oracle 中应该是 parent_uuid is null
  • 这个数据库是用jpa搭建的,我没有参与它的项目,不能修改实际结构,所以我不能将parent_uuid存储在geonodes表中。 geoparents 没有 parent_uuid 等于 null 的行,根是永远不会出现在 children 列中的父级。
  • @StefaniaLori:那你应该START WITH child_uuid IS NULLSELECT parent_uuid uuid 而不是child_uuid
  • 抱歉,我忘记指定连接表(geoparents)中没有任何空值。所有对都对应于现有地理节点的 uuid,并且有两个 fk 维护数据完整性。
  • 是否有多个根节点?如果只有一个根节点,您可以通过硬编码来逃脱。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多