I have a categories table in MySql something like this:
categoryId | categoryTitle | definedField | parentId
1 Title 123 NULL
2 AnotherTitle 234 1
3 AndAnotherOne NULL 1
What I need to do is find the closest definedField value by going up to parent,like this;
Since category 2 has a definedField, return its value;
Since category 3 does not have a definedField, search up, to its parent. It has definedField, so return it. If it didn’t have one, search up until find one.
There will ALLWAYS be the topmost category that will have definedField set. I only need to find a good algorithm to search for this in a MySQL InnoDb table.
There is no direct way of retrieving hierarchical data in MySQL (like, for example, Postgres’s RECURSIVE query). There is a good article summarizing different ways of implementing nested data set in MySQL: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
The article covers two models: Adjacency List and Nested Set.
The Adjacency List Model
The Nested Set Model