CREATE TABLE `empTest` (
`keysearch` INT(8) NOT NULL,
`flg_manager` INT(1) NOT NULL,
`fk_manager` INT(8) NOT NULL,
PRIMARY KEY (`keysearch`)
)
INSERT INTO `empTest` (`keysearch`, `fk_manager`, `flg_manager`) VALUES ('5407', '5866', 0);
INSERT INTO `empTest` (`keysearch`, `fk_manager`, `flg_manager`) VALUES ('5866', '0679', 0);
INSERT INTO `empTest` (`keysearch`, `fk_manager`, `flg_manager`) VALUES ('0679', '9177', 1);
INSERT INTO `empTest` (`keysearch`, `fk_manager`, `flg_manager`) VALUES ('9177', '0011', 1);
In the example data above there are 3 users (4th being the last line manager). I would like to be able to select the "1st keysearch where they have the flg_manager set as 1" as AuthManager (indicating they are an Authorising manager)
The query result I am looking to achieve is:
Keysearch,AuthManager
5407,0679
5866,0679
0679,9177
I am thinking it needs to be a loop but I really don't know where to start. I understand I need to use the middle employee as a Join to be able to see from employee 5407 to employee 0679. Annoyingly in this example there is only one employee to 'jump' but I need to be able to account for up to 8 jumps.
Completely Wrong - but I'm at a complete loss...
SELECT e.keysearch, @manager AS manager
FROM emptest e, emptest m1, emptest m2
WHERE @manager = CASE WHEN (
SELECT e.fk_manager
FROM e
WHERE e.fk_manager = m1.keysearch AND m1.flg_manager = 1)
Else When...
Will I need to do lots of Case loops?
Any Suggestions? Running MariaDB 10.3.