Assume the following table records:
TABLE: foo
==========================
| foo_id | foo_parent_id |
==========================
| 1 | NULL |
| 2 | NULL |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 1 |
| 7 | 2 |
| 8 | 1 |
| 9 | NULL |
--------------------------
I want to get, say, the first 10 parent records (those records with foo_parent_id = NULL) immediately followed by, say, the first 2 child records of that parent record. So, I’m looking for a result like this:
1, NULL
3, 1
5, 1
2, NULL
4, 2
7, 2
9, NULL
How do I query something like this?
Here’s one idea. But it’s based on lots of assumptions about the way your data is setup. Ever increasing IDs down the tree, only two levels, etc.
–give me the top X number of parent_ids
(This is good, you just adjust the LIMIT 10 to vary the number of parent levels to show)
(This part is kind of hacky, as you have to put an ever longer string of these to get past two children)
–it’s the first child, or…
–it’s the second child, or…
–it’s the parent
So what we’re doing here is basically ordering by the parent_id column and then the child columns underneath it with a slight twist. If the parentid column is NULL then we use the actual ID. This means that for ordering purposes our table looks like this:
Then we multiply that ordering column *100
and lastly we add our foo_id column to it
Now we order the table by that virtual column and…
There we go!