2012-11-30 65 views
0

我有一個表是這樣的:如何列出自我關係表?

+----+-------+--------+ 
| id | title | parent | 
+----+-------+--------+ 
| 1 | text1 | NULL | 
+----+-------+--------+ 
| 2 | text2 | NULL | 
+----+-------+--------+ 
| 3 | text3 | NULL | 
+----+-------+--------+ 
| 4 | text4 | 1 | 
+----+-------+--------+ 
| 5 | text5 | 1 | 
+----+-------+--------+ 
| 6 | text6 | 2 | 
+----+-------+--------+ 
| 7 | text7 | 3 | 
+----+-------+--------+ 
| 8 | text8 | 5 | 
+----+-------+--------+ 

「父」是外鍵「ID」 ,我想在HTML列出這些行。

名單應該是這樣的:

• text1 
    ○ text4 
    ○ text5 
     ♦ text8 
• text2 
    ○ text6 
• text3 
    ○ text7 

我需要sql_code和PHP。

感謝...

+0

用MySQL,你需要做的是在應用程序代碼的MySQL不支持遞歸查詢(不同於其他DBMS ) –

+0

爲什麼文本7在text5下?爲什麼text1兩次? – fthiella

+0

你應該通過http://stackoverflow.com/questions/11064913/achieve-hierarchy-in-a-less-number-of-mysql-queries 這將是對你有幫助 –

回答

1

你應該看看managing hierarchical data with MySQL

SELECT 
    t1.title AS lev1, t2.title as lev2, t3.title as lev3, t4.title as lev4 
FROM 
    category AS t1 
LEFT JOIN 
    category AS t2 ON t2.parent = t1.id 
LEFT JOIN 
    category AS t3 ON t3.parent = t2.id 
LEFT JOIN 
    category AS t4 ON t4.parent = t3.id 

請注意,文章建議從普通PARENT_ID/ID設置了不同的方法。

+0

如果級別不是像在 中那樣不變怎麼辦?http://stackoverflow.com/questions/11064913/achieve-hierarchy-in-a-less-number-of-mysql-queries –

0

上面MySQL的代碼是優秀的。這是我的PHP代碼舉手之勞

while($lev = mysql_fetch_array($category)){ 

    echo $lev['lev1']; 
    echo '<br>'; 
    if($lev['lev2'] != NULL) 
    { 
     &nbsp;echo $lev['lev2']; 
     echo '<br>'; 
     if($lev['lev3'] != NULL) 
     { 
      &nbsp;&nbsp;echo $lev['lev3']; 
      echo '<br>'; 
      if($lev['lev4'] != NULL) 
      { 
       echo $lev['lev4']; 
      } 
     } 
    } 
}