高效实施亲子关系的逻辑

发布于 2024-08-15 16:09:58 字数 396 浏览 3 评论 0原文

我有一个表,其中父子关系存储为:
子 ID 名称 父 ID
1 A1 空
2 A2 1
3 B1 空
4 A3 2
5 A4 1
我正在使用 Objective C,我需要以以下方式生成一个文本文件:
名称=A1> 名称=A2> 姓名=A3>> 名称=A2/>
名称=A4/>
姓名=B1>>

我使用的方法是首先捕获最后一个元素(Id=5),然后检查所有其他节点以获取其父节点。 n 复杂度为 n*n-1,是否有其他更好的方法,因为当我们在数据库中有大量数据时,这种方法并不成功。

数据库结构是灵活的,我们可以改变它,如果有更好的东西......

寻求您的帮助和支持。

I have a Table where Parent Child Relation ship is stored as:
ChildID Name ParentID
1 A1 Null
2 A2 1
3 B1 Null
4 A3 2
5 A4 1
I m Woking on Objective C and I need to Generate a text File in Manner:
Name =A1>
Name =A2>
Name =A3/>
Name =A2/>
Name =A4/>
Name =B1/>

I was using a approch where I catch the Last Element (Id=5) first and then checking all other nodes to get its Parent Nodes. n Complexity comes to be as n*n-1, Is there any other better approach as this approach is not a succes when we have lasrge data in Database.

Database Structure is flexible, we can change that, if there is something better...

Looking for your help and support.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

留一抹残留的笑 2024-08-22 16:09:58

从您的输出结构来看,我假设您的数据代表一棵树。因此,您有一个简单的“获取节点的所有子节点”请求,如 SELECT childId, name FROM tree WHERE ParentId = ?,它允许您执行标准的树遍历。伪代码:

def displayNode(node)  
  children = selectChildren(node.id)
  if (empty(children)) 
    print '<'+node.name+'/>'
  else 
    print '<'+node.name+'>'
    for (child in children) 
      displayNode(child)
    print '</'+node.name+'>'

如果每个节点运行一个查询太多(可能就是这种情况),则一种优化是运行单个查询来获取所有数据并将其放入优化的数据结构中:

for (node in selectAllNodes())
  nodes[node.parent].append(node);

def selectChildren(id)
  return nodes[id]

From your output structure, I assume your data represents a tree. You therefore have a simple "get all children of a node" request as SELECT childId, name FROM tree WHERE parentId = ?, which lets you perform a standard tree traversal. Pseudocode:

def displayNode(node)  
  children = selectChildren(node.id)
  if (empty(children)) 
    print '<'+node.name+'/>'
  else 
    print '<'+node.name+'>'
    for (child in children) 
      displayNode(child)
    print '</'+node.name+'>'

An optimization, if running one query per node is too much (which probably is the case) is to run a single query to fetch all the data and place it in an optimized data structure:

for (node in selectAllNodes())
  nodes[node.parent].append(node);

def selectChildren(id)
  return nodes[id]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文