Vex Star

Vex Star

Computers and Programming

Vex Star RSS Feed
 
 
 
 

Parent/Child data

This is the content of my table called "Category"

Is this possible through a query alone or do I need to read ALL the data into memory and then recursively sort it all?

This is in PHP+MySQL btw.

mysql> select id, name, parentid from category;
+----+-----------+----------+
| id | name      | parentid |
+----+-----------+----------+
|  1 | category1 |        0 |
|  2 | category2 |        3 |
|  3 | category3 |        0 |
|  4 | category4 |        2 |
|  5 | category5 |        0 |
+----+-----------+----------+

I need to be able to do an SQL query that lists the items in order. So I’d like to see something like this:

+----+-----------+----------+
| id | name      | parentid |
+----+-----------+----------+
|  1 | category1 |        0 |
|  3 | category3 |        0 |
|  2 | category2 |        3 |
|  4 | category4 |        2 |
|  5 | category5 |        0 |
+----+-----------+----------+

Which visually would look like this:

- category1
- category3
- - category2
- - - category4
- category5

What’s your logic behind the sorting?
for building the tree, though, you’ll need to do some recursion

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply