I have this recursive SQL query where I obtain the hierarchy of IDs of every office (an office belongs to higher rank office and such) - inspired by @leftclickben's answer in How to do the Recursive SELECT query in MySQL?:
select @pv := o.office_id, o.display_name, (
select concat(concat(group_concat(@pv := t.parent_office_id order by t.parent_office_id asc SEPARATOR '.' ), '.'), t.office_id) pivot
from (select * from office order by (CASE WHEN parent_office_id < office_id THEN parent_office_id END) DESC,
(CASE WHEN parent_office_id > office_id THEN parent_office_id END) ASC) t
where t.office_id = @pv
) 'hierarchy'
from office o
group by o.office_id
order by o.office_id asc, o.parent_office_id desc
;
For this query to work, it needs perferct descendance or ascendance to be verified. This property is not verified in my data, and thus I had to take advantage of selective order by in the subquery.
I obtained very encouraging results (80% accuracy), and I was wondering if anyone could suggest more techniques to obtain better results?
Examples:
- for some office (ID = 97), its hierarchy is 1.2.4.14.97 (accurate value);
- for another case (ID = 101), I get: 111.101 (broken hierarchy);
In a nutshell, all results must start with 1.
A good sample: