3

我的表有 id 和 perent 如下:

id   parent
12      0
21      12
34      12
47      21
57      21
66      21
77      34
88      47

我想编写查询获取 id 并返回这个 id 的级别:

例如

1 => level 1
2 and 3 => level 2
4 => level 3
... and so on.

我尝试了什么:

SELECT cc1.id, count(cc1.id) c FROM community_comments cc1
inner join community_comments cc2 on cc1.id = cc2.parent 
AND cc1.parent = 324 group by cc1.parent

这将返回 324 级以下多少级,这不是我想要的

4

1 回答 1

2

我正在使用 PHP 代码解决它

function get_comment_level($comment_id){

        $query = "select parent from community_comments where id = $comment_id";

        $result = $this->conn->db_query($query);

        $level = 1;
        $parent = 0;

        while ($row = $this->conn->db_fetch_object($result)){
            $parent = $row->parent;
        }

        if ($parent != 0) {
            $level = $this->get_comment_level($parent);
            $level++;
        }

        return $level;
    }
于 2013-08-29T07:55:33.327 回答