mysql - Conditional SELECT -


i have single directory table contains employees , immediate managers. i'm trying loop through reporting hierarchy return reporting line far necessary - when hit no manager (i.e ceo) can stop. rather looping through bunch of php if/else statements, i'm trying in 1 mysql query.

best effort far has been:

select d1.empno d1, d2.empno d2, d3.empno d3, d4.empno d4, d5.empno d5, d7.empno d7, d8.empno d8 `directory` d1 left join directory d2 on d1.manageremp = d2.empno left join directory d3 on d2.manageremp = d3.empno left join directory d4 on d3.manageremp = d4.empno left join directory d5 on d4.manageremp = d5.empno left join directory d6 on d5.manageremp = d6.empno left join directory d7 on d6.manageremp = d7.empno left join directory d8 on d7.manageremp = d8.empno d1.empno = '38414' 

but returns 8 results regardless of whether it's necessary. if i'm retrieving hierarchy 2 steps below ceo get

d1     d2     d3    d4   d5   d6   d7   d8 13307  55192  10917 null null null null null 

whereas want this:

d1     d2     d3 13307  55192  10917 

so want select next empno if previous manageremp not null. stuff doesn't seem work:

select d1.empno d1,  case  when d1.manageremp not null d2.empno end d2,  case  when d2.manageremp not null d3.empno end d3, case  when d3.manageremp not null d4.empno end d4, ... 

i'm sure there's elegant solution i'm not seeing it. ideas?


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

javascript - Clean way to programmatically use CSS transitions from JS? -

android - send complex objects as post php java -