简体   繁体   中英

How do I get all sub-categories related to a category without the knowing how deep it goes.

This is a category table,

CREATE TABLE `categories` (
  `id` int(11) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `parentid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

This is how you get Category and related Sub-Category.

SELECT root.name  AS root_name
     , down1.name AS down1_name
     , down2.name AS down2_name
  FROM categories AS root
LEFT OUTER
  JOIN categories AS down1
    ON down1.parentid = root.id
LEFT OUTER
  JOIN categories AS down2
    ON down2.parentid = down1.id

 WHERE root.parentid IS NULL
ORDER 
    BY root_name 
     , down1_name 
     , down2_name

SQLfiddle

What I have noticed is that this query goes only 2 step/nodes forward, like say

category > sub-category 1 > sub-category 2

What if I have a sub-category that goes beyond 2 step/nodes like say

category > sub-category 1 > sub-category 2 > sub-category 3

or even may be sub-category 4 do I need to add down3.name or down4.name to get to the end to include all sub-category or is there a better way?

You can get the complete hierarchy of an item using a recursive query.

ex:

    select c.id,c.name,@parent := c.parentid 
from 
 (select * from categories order by id desc) c
join 
 (select @parent := 16) t
where c.id =@parent

create a stored procedure to obtain the desired output for all item ids recursively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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