开发者

Get a leaf nodes by recursive query

开发者 https://www.devze.com 2023-04-07 04:18 出处:网络
I have a categories structure as follows I want to select leaf node. i mean the the categories who don\'t have sub categories.

I have a categories structure as follows

Get a leaf nodes by recursive query

I want to select leaf node. i mean the the categories who don't have sub categories.

In my database monitor, cpu, novels and comics will be answer.

Any help will be appreciated.

Edit : I tried this.

public function get_valid_categories($parent)
        {
                $has_childs = false;
                foreach($this->categories a开发者_运维知识库s $key => $value) {
                    if ($value['parent'] == $parent) {
                        if ($has_childs === false) {
                            $has_childs = true;
                        }
                        else
                        {
                            $this->valid_categories[] =  $value['name'];
                        }
                        $this->get_valid_categories($key);

                    }
                }
                if ($has_childs === true)
                {
                    return $this->valid_categories ;
                }
        }

and i m calling this function as follows

get_valid_categories(0);


You don't need a recursive query for this. How about the following SQL:

select t1.* 
from table t1
    left join table t2 on t1.id = t2.parent_id
where t2.id is null

This takes the rows in your table and self-joins to get each row's children. It then filters out those rows that have no children by checking for t2.id is null.


Well, there are probably many possible solutions but here is the first one that came to my mind:

SELECT *
FROM categories
WHERE id NOT IN (
                 SELECT DISTINCT(parent_id) FROM categories
                )

Not so elegant as using joins, but can be an alternative solution for the problem. Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消