你的查詢是不正確的 - 如果你真的想建立一個樹,你需要查詢,它會提供一個,這意味着分層的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並對其進行排序) 。
這真的是查詢嗎? ... FROM employee_master AS t1「+」...這是什麼?這甚至可以起作用嗎? – user489872
對不起,我只是把我的java代碼,其中superior_id將被替換爲真正的ID –
是這個MySQL或其他? – user489872