Здесь вы go:
with
x as (
select
empid as startid, 0 as level,
empid, cast(concat('', deptid) as varchar(255)) as chain
from employee where empid = 1
union all
select
x.startid, x.level + 1,
e.empid, cast(concat(chain, '-', e.deptid) as varchar(255))
from x
join rel r on r.from_eid = x.empid
join employee e on e.empid = r.to_eid
),
y as (
select startid, max(level) as max_level from x group by startid
)
select x.chain
from x
join y on x.startid = y.startid and x.level = y.max_level
Результат:
chain
--------
M1-E1-I1
Для справки я использовал скрипт данных:
create table employee (
empid int,
empname varchar(10),
role varchar(10),
deptid varchar(10)
);
create table rel (
from_eid int,
to_eid int
);
insert into employee (empid, empname, role, deptid) values
(1, 'John', 'Manager', 'M1'), (2, 'George', 'Employee', 'E1'),
(3, 'Alex', 'Intern', 'I1'), (4, 'Bob', 'Employee', 'E2');
insert into rel (from_eid, to_eid) values
(1, 2), (2, 3);