簡體   English   中英

MySQL 5.7 對未知級別的層次結構數據的遞歸查詢

[英]MySQL 5.7 recursive query on hierarchy data with unknown levels

我正在開發一個層次結構數據結構,我想在其中執行遞歸以獲得所需的輸出

 id       role_id      reporting_to
 ------+-------------+-----------------
1          100             101
1          101             102
1          102             103
1          103             104

如果我給103作為輸入角色,我想得到以下輸出

  id    role_id      reporting_to
-----------+-------------+-----------------
    1          100             101
    1          101             102
    1          102             103

輸出應該是從輸入到最后一個孩子。 嘗試了以下示例,但沒有返回正確的輸出

select id,role_id,reporting_to
from (select * from role_mapping order by reporting_to,id) rm_sorted,
     (select @r:='103') initialisation
where find_in_set(reporting_to, @r)
and length(@r := concat(@r, ',', role_id))

除非使用函數,否則mysql5.7 永遠無法進行遞歸查詢。

也可以使用其他有遞歸的語言,比如mysql5.8、oracle、java等,生成路徑列,像這樣(假設104是根節點)

ID role_id 報告給 小路
1 100 101 104/103/102/101/100
1 101 102 104/103/102/101
1 102 103 104/103/102
1 103 104 104/103

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM