See https://www.sitepoint.com/hierarchical-data-database-2/ for explanation of a MPTT.
I have a table that stores hierarchical data same as the link above except that it has an additional column called level
to store the depth of the MPTT where level 0 is for the root node and the number increases for the descendant nodes.
Assuming I am using MySQL, what is the query to get the ancestor nodes given a node and the level we want?
E.g. in a 4 level hierarchical table, meaning level 0-3, and I give you a particular node which is at level 3 and I want to find its ancestors at level 1 only
How do I write a query like that?
Update:
I have been wrongly accused of duplicating this question How to create a MySQL hierarchical recursive query I will make it clearer how my question is different:
That question is asking and I quote "find its child ids". I am looking for the opposite.
I am looking for the ancestors nodes at a particular level given a node. That part of the question was bold. I even stated as much in my question title.
I will happily delete this question if I do find a duplicate that is asking the exact same thing.
Let me modify the example from http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ to make this clearer
+-------------+----------------------+--------+------+----+-----+
| category_id | name | parent | lft | rgt |level|
+-------------+----------------------+--------+-----+-----+-----+
| 1 | ELECTRONICS | NULL | 1 | 20 | 0 |
| 2 | TELEVISIONS | 1 | 2 | 9 | 1 |
| 3 | TUBE | 2 | 3 | 4 | 2 |
| 4 | LCD | 2 | 5 | 6 | 2 |
| 5 | PLASMA | 2 | 7 | 8 | 2 |
| 6 | PORTABLE ELECTRONICS | 1 | 10 | 19 | 1 |
| 7 | MP3 PLAYERS | 6 | 11 | 14 | 2 |
| 8 | FLASH | 7 | 12 | 13 | 3 |
| 9 | CD PLAYERS | 6 | 15 | 16 | 2 |
| 10 | 2 WAY RADIOS | 6 | 17 | 18 | 2 |
+-------------+----------------------+--------+-----+-----+-----+
My question would be given a node and the ancestor level, give me the ancestor node. In other words, if I was given the node 8 (which is the Flash) and also the level 1, I am expecting the answer to be 6 (the portable electronics)
I hope that makes it a lot clearer.