0

I have a table that looks like:

enter image description here

What I want to do is output the main categories (those with null category_id) and under each one, list the categories that have that category_id as the parent. That way, I create a little hierarchy output.

I could do this simply by doing a query that grabs all of the categories with null parent. Then doing another query that finds the categories with that as its parent. However, I am confident there's a way to do this in PHP/MySQL with only one query.

Any help, even conceptually, would be greatly appreciated!

j08691
  • 204,283
  • 31
  • 260
  • 272
Chris Farrugia
  • 1,024
  • 3
  • 17
  • 35

2 Answers2

1

You can get all categories at once from the database and build your hierarchical structure with a recursive function, see: Convert a series of parent-child relationships into a hierarchical tree?

Community
  • 1
  • 1
jeroen
  • 91,079
  • 21
  • 114
  • 132
1
SELECT COALESCE( c2.category_order, c1.category_order ) as top_order,
             c1.*
FROM categories c1
LEFT JOIN categories c2
ON c1.parent_category_id = c2.category_id
ORDER BY top_order, c1.category_order
piotrm
  • 12,038
  • 4
  • 31
  • 28