I am using MariaDB to store hierarchical items whose key is a string of identical length.
It is the key that encodes the relationships (parent, child, ancestor, descendant, none) as follows.
- The leftmost non-zero character-substring of the key identifies an item, with the rest of the string a pad of zeros.
- If the two keys of any two items A and B differ at the first character, A and B are not related (they don't have a common ancestor)
- otherwise A and B are related with A being the ancestor of B if the leftmost non-zero character-substring of A is a substring of the leftmost non-zero character-substring of B. In other words if the position of the leftmost zero character in the key for A is less than the position of the leftmost zero character in the key for B i.e. if the pad of zeros in A is greater in length than the pad of zeros in B.
I would like to write an SQL query code that takes a string (a possible key) and returns the ancestors keys of this string. I am able to write the version that returns the descendants as follows. I first remove the zero-character pad on the right of the candidate string then issue the following...
SELECT keys FROM items WHERE LEFT( key, CHAR_LENGTH(string) ) = string
but writing one that returns the ancestors is a headache. Please help me.