0
votes

I am having one category table where i want to give category for posts

post_category(cat_id,cat_name,parent_id,cat_count)

cat_id    cat_name       parent_id       cat_count
   1           C            NULL           300 
   2         Pointers        1             100
   3         Structures      1             200
   4          Java          NULL           700    
   5         Exceptions      5             200
   6         Threading       5             300
   7         Thread Priority 6             200

here cat_id is primary key and parent id for root elenemts are null and for child parent id is any valid cat_id. I want to select each parent and its child details. as follows

      C
         Pointers
         Structures    

      Java
         Exceptions
         Threading 
             Thread priority 
2
Have you considered the nested set model? It might be worth it if your tree gets deeper. (How do you order siblings at the moment?) - DCoder
@DCoder nesting level is only 2 - xrcwrn
you should go for some server-side coding also along with Mysql. - Kalpesh

2 Answers

1
votes

Unfortunately, MySQL does not support a variable number of JOINs, as MS SQL (and I think Postgres?) do. However, if you are willing to re-evaluate the schema, there has been some good thinking on the matter, and there are several good options in this presentation by Bill Karwin at Percona

As it stands, you have essentially two options:

  1. Choose an arbitrary depth to query to
  2. Select every single record and do the aggregation in your application layer (ick!)
0
votes

In MS SQL I think you'd need to use Recursive Queries Using Common Table Expressions. So perhaps that might help find what you're looking for in the MySQL space.