您好,登錄后才能下訂單哦!
這篇文章主要介紹了MySql如何利用父id遞歸向下查詢子節點,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
不用寫存儲過程,不用建數據庫函數,一段sql就可以實現
SELECT ID.LEVEL, DATA.* FROM ( SELECT @ids AS _ids, ( SELECT @ids := GROUP_CONCAT( region_id ) FROM region WHERE FIND_IN_SET(parent_id, @ids ) ) AS cids, @l := @l + 1 AS LEVEL FROM region, ( SELECT @ids := 3, @l := 0 ) b WHERE @ids IS NOT NULL ) ID, region DATA WHERE FIND_IN_SET( DATA.region_id, ID._ids ) ORDER BY LEVEL
測試
--創建測試環境 create table t_test( id int PRIMARY key, parent_id int, name varchar(200) ) insert t_test VALUES(1,null,"中國"); insert t_test VALUES(2,1,"華北"); insert t_test VALUES(3,2,"山西省"); insert t_test VALUES(4,2,"北京"); insert t_test VALUES(5,3,"臨汾市"); insert t_test VALUES(6,4,"北京市"); insert t_test VALUES(7,5,"堯都區"); insert t_test VALUES(8,6,"朝陽區"); insert t_test VALUES(9,7,"解放西路"); insert t_test VALUES(10,8,"朝陽北路"); SELECT * FROM t_test;
測試數據展示
查詢 id=1,查詢中國下邊有哪些地方
SELECT ID.LEVEL, DATA.* FROM ( SELECT @ids AS _ids, ( SELECT @ids := GROUP_CONCAT( id ) FROM t_test WHERE FIND_IN_SET(parent_id, @ids ) ) AS cids, @l := @l + 1 AS LEVEL FROM t_test, ( SELECT @ids := 1, @l := 0 ) b WHERE @ids IS NOT NULL ) ID, t_test DATA WHERE FIND_IN_SET( DATA.id, ID._ids ) ORDER BY LEVEL
id=3,查詢山西下邊有哪些地方
SELECT ID.LEVEL, DATA.* FROM ( SELECT @ids AS _ids, ( SELECT @ids := GROUP_CONCAT( id ) FROM t_test WHERE FIND_IN_SET(parent_id, @ids ) ) AS cids, @l := @l + 1 AS LEVEL FROM t_test, ( SELECT @ids := 3, @l := 0 ) b WHERE @ids IS NOT NULL ) ID, t_test DATA WHERE FIND_IN_SET( DATA.id, ID._ids ) ORDER BY LEVEL
id=4,查詢北京下邊有哪些地方
最后再從 id=2 華北地區往下查詢
感謝你能夠認真閱讀完這篇文章,希望小編分享的“MySql如何利用父id遞歸向下查詢子節點”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。