我有一张这样的表:
+----+-------+--------+
| 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 |
+----+-------+--------+
“parent”是“id”的外键 我想在html中列出这些行。
列表应该是这样的:
• text1
○ text4
○ text5
♦ text8
• text2
○ text6
• text3
○ text7
我需要sql_code和php。
感谢...
答案 0 :(得分: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设置不同的方法。
答案 1 :(得分:0)
以上MySQL代码非常好..这是我对PHP代码的一点努力
while($lev = mysql_fetch_array($category)){
echo $lev['lev1'];
echo '<br>';
if($lev['lev2'] != NULL)
{
echo $lev['lev2'];
echo '<br>';
if($lev['lev3'] != NULL)
{
echo $lev['lev3'];
echo '<br>';
if($lev['lev4'] != NULL)
{
echo $lev['lev4'];
}
}
}
}