你可以看一下這篇文章的一些可能的方式:http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/(最初它是根據mysql.com出版,但後來刪除)
爲你的數據,你可以嘗試類似以下內容:
CREATE TABLE `tree` (node_id INT NOT NULL,
parent_id INT NOT NULL);
INSERT INTO `tree`(node_id, parent_id) VALUES(2,0),
(3,2),
(4,2),
(6,2),
(7,4),
(8,4),
(9,8);
SELECT t1.node_id AS lev1, t2.node_id AS lev2, t3.node_id AS lev3, t4.node_id AS lev4
FROM tree AS t1
LEFT JOIN tree AS t2 ON t2.parent_id = t1.node_id
LEFT JOIN tree AS t3 ON t3.parent_id = t2.node_id
LEFT JOIN tree AS t4 ON t4.parent_id = t3.node_id
WHERE t1.node_id = 4;
你試過了什麼?附:歡迎來到Stack – George 2013-03-25 10:12:48
我試過遞歸函數,但問題是我沒有從什麼地方返回數組。 – Shafeeque 2013-03-25 10:20:52