繁体   English   中英

在mysql或php中获取父级的所有后代?

[英]Get all descendants of parent in mysql or php?

希望在这里对大家有所帮助。 说我有一个像这样的mysql表

ID | Content | Parent ID |
2  | A       | 0
3  | A       | 2
4  | A       | 3  
5  | A       | 4
6  | A       | 10
7  | A       | 0
8  | A       | 7
9  | A       | 8
10 | A       | 9

我想要ID 2的所有后代。

3是孩子。 孙子将是父母ID为3的任何帖子。依此类推。

在这种情况下, ID 2的后代是ID's 3, 4 and 5

ID 7的后代是ID's 8, 9, 10 and 6

无论如何,我可以在MySQL中查询它,而对祖先的深度没有限制? 甚至遍历php中的结果集?

非常感谢。

getTree()将返回带有嵌套子项的父节点。 您可能需要根据您的框架更改PHP mysql查询。

public function getTree($nodeId) {
    $mainNode = $this->db->select('id, content')->from('table_name')->where('id', $nodeId)->get()->first_row();
    $this->recur($mainNode);
    return $mainNode;
}

public function recur(&$node) {
    $q = $this->db->select('id, content')->from('table_name')->where('parent_id', $node->id)->get();
    if($q->num_rows() == 0) {
        return;
    }

    if($q->num_rows() > 0) {
        $node->children = $q->result(); // array of all child nodes
        foreach ($node->children as $u) {
            $this->recur($u);
        }
    }
}

您可以这样完成:(我将使用伪代码给您一个大概的想法)

$res = get_res('select * from my_table');

$descendants = get_descendants(2); 

function get_descendants ($parent_id, $res) {
    foreach ($res as $row) {
        if ($row['parent_id'] == $parent_id) {
            $descendants[] = $row['id']; 
            $descendants = $descendants + get_descendants($row['id'], $res);
        }
    }
    return $descendants;
}

您必须规范化数据库https://en.wikipedia.org/wiki/Database_normalization

我理解你这样的问题:

论坛(父级)
----第一届论坛----
forum_id = 1
forum_name = PHP

线程(子)

----第一记录----
thread_id = 20
forum_id = 1
----下一条记录----
thread_id = 21
forum_id = 1

帖子(孙子)

然后您可以使用联接来访问(例如)规范化数据库,如果您在主题表中,则可以在一个查询中访问它所属的论坛以及特定主题中的帖子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM