2017-02-07 35 views
1

標準,我在數據庫中的一個職員表都列emp_id爲,superior_id,姓名等排序ArrayList的基於使用SQL查詢或Java

我想用JS庫生成樹。

除經理外,每位員工都有superior_id。所以JS輸入我想應該是這樣

manager names -- lead name-- employee name employee name employee name lead name
employee name lead name employee name

,但我得到的結果是一樣

manager name lead name lead name
lead name employee name employee name employee name employee name employee name

我寫SQL查詢是

SELECT 
    t1.emp_id, 
    t1.emp_name, 
    t1.tcs_mail, 
    t1.boeing_mail, 
    t1.contact_no, 
    t2.emp_id as superior_id 
FROM employee_master AS t1 
LEFT JOIN employee_master AS t2 ON t2.emp_id = t1.superior_id 
LEFT JOIN employee_master AS t3 ON t3.emp_id = t2.superior_id 
ORDER BY t3.emp_id,t2.emp_name LIMIT 10 

請幫助我。

+1

這真的是查詢嗎? ... FROM employee_master AS t1「+」...這是什麼?這甚至可以起作用嗎? – user489872

+0

對不起,我只是把我的java代碼,其中superior_id將被替換爲真正的ID –

+0

是這個MySQL或其他? – user489872

回答

0

你的查詢是不正確的 - 如果你真的想建立一個樹,你需要查詢,它會提供一個,這意味着分層的SQL查詢。

不幸的是,我沒有真正能夠找到簡單的方法來構建MySQL方言的分層查詢。如果你只知道,總會有你的樹的不超過三個嵌套級別,您可以使用多個計數器來模擬層次:

with first_level(emp_id, emp_name, rnum, rnum2, rnum3) as (
    -- first we retrieve all employees that do not have any superiors 
    -- there first counter is ordering of those employees, other counters are zero (see below) 
    select emp_id, emp_name, ROW_NUMBER() OVER (order by emp_name) as rnum, 0 as rnum2, 0 as rnum3 
    from employee_master 
    where superior_id is null 
), 
    second_level(emp_id, emp_name, rnum, rnum2, rnum3) as (
    -- then we need subordinates of top superiors. There first counter should represent ordering of the superior 
    -- second counter should represent ordering of the subordinate and last counter is zero 
    select s.emp_id, s.emp_name, f.rnum, ROW_NUMBER() over (order by f.rnum, s.name) as rnum2, 0 as rnum3 
    from employee_master s 
    inner join first_level f on f.emp_id = s.superior_id 
), 
    third_level(emp_id, emp_name, rnum, rnum2, rnum3) as (
    -- our last query level. It will have first two counters joined from higher levels and last counter will be the own level ordering 
    select s.emp_id, s.emp_name, f.rnum, f.rnum2, row_number() over (order by f.rnum, f.rnum2, s.name) as rnum3 
    from employee_master s 
    inner join second_level f on f.emp_id = s.superior_id 
) 

-- lastly, we combine all of the above into a single query: 
select 
    emp_id, 
    emp_name, 
    rnum, rnum2, rnum3 
from first_level 
union all 
select 
    emp_id, 
    emp_name, 
    rnum, rnum2, rnum3 
from second_level 
union all 
select 
    emp_id, 
    emp_name, 
    rnum, rnum2, rnum3 
from third_level 
order by rnum, rnum2, rnum3 

注意,因爲我已經使用條款,上述查詢僅在MySQL 8.0及以上版本中有效。

您還可以在這裏看到更多的通用的解決方案:ExplainExtended:Hierarchical Queries in MySQL

編輯: 這裏也是關於如何在MySQL 8.0及以上建造分層自連接查詢的一些材料:MySQL Server Team:Recursive Common Table Expressions。 這可能會幫助您解決最大樹高可能無限的問題,但看起來它可能需要您跳過一些環節才能實現正確的排序(例如,獲取當前的樹巢級別,將其拼接到varchar並對其進行排序) 。