在mysql查询中获取子级别

时间:2013-08-29 07:36:09

标签: mysql

我的表有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级以下多少级别,这不是我想要的

1 个答案:

答案 0 :(得分: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;
    }