Simple question.. just can’t get the result set in the order I need :p
I have a table “categories”
id | name | parent
1 apple 0
2 macintosh 1
3 atari 0
4 st 3
5 lisa 1
I’m trying to select get the following result set:
1 apple 0
5 lisa 1
2 macintosh 1
3 atari 0
4 st 3
So in other words I want all columns of all rows, where rows with parents are immediately after their parent row and all are sorted alphabetically.
parent a
child a
child b
parent b
child a
The query I’m using now doesn’t correctly re-order the rows after their parents
SELECT a.*, b.* FROM categories a RIGHT JOIN categories b ON b.parent = a.id
For a simple, perhaps suboptimally-scalable solution, I recommend hard-coding this with the maximum number of levels you will have:
For 2 levels only:
You’re really asking about sorting, so I’d recommend generating a “path”-like string:
(see below for sample output of this query)
For 3 levels, though your data doesn’t have this yet — path omitted because it will get ugly 🙂
A more comprehensive solution for quickly selecting all items in a particular category at any level, which does require some work on all writes, is implementing a ‘right’ and ‘left’ numbering concept. But, further discussion on that is almost certainly going beyond the scope of what you’re asking. However, that’s the only good way in my experience to make this kind of self-referencing table very useful if it’s going to get big (maybe after 1000+ rows with 3 to 10 levels).
Addendum: sample output from the second query: