我在php和mysql中工作,我有一个表类,我需要在父类别下显示子类。像
CAT1
-> Subcat1
-> Subcat11
-> Subcat2
--> Subcat21
--> Subcat211
CAT2
-> Subcat2
-> Subcat21
-->Subcat22
-> Subcat3
--> Subcat31
--> Subcat311
我的表结构如下:
CREATE TABLE IF NOT EXISTS `category` (
`cat_id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'This is primary key of the table',
`name` varchar(255) DEFAULT NULL,
`parent_cat_id` bigint(11) NOT NULL,
PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
你可以帮我解决一下,如何执行我的查询。
答案 0 :(得分:1)
示例:
<?php
class RightMenu {
public $menu;
public $patch = '';
public function getMenu($parent = 0) {
$DB = new DataBase();
$result = $DB->exec("SELECT * FROM cont_sections WHERE parentid = $parent AND status = 1 ORDER BY name;");
if(mysql_num_rows($result) > 0) {
echo '<ul>';
while($row = mysql_fetch_assoc($result)) {
if($row['parentid'] == 0){
$this->patch = '';
}
$this->patch .= '/' . $row["translit"];
echo '<li><a href="/section'.$this->patch.'.html">' . $row["name"] . '</a>';
echo $this->getMenu($row["id"]);
echo '</li>';
}
echo '</ul>';
}
mysql_free_result($result);
unset($DB);
}
}
?>
答案 1 :(得分:0)
你需要写一个递归函数来显示Category&amp;子猫
getAllSubCats(0);
function getAllSubCats($cat, $depth = NULL)
{
$this_cat = mysql_fetch_object(mysql_query("select * from categories where id= '$cat'"));
$indent = str_repeat(" ", $depth);
echo $indent . $this_cat->name . "<br />";
$result = mysql_query("select * from categories where parent_cat_id = '$cat'");
while($cat = mysql_fetch_object($result))
{
getAllSubCats($cat->id, $depth + 1);
}
}
或使用以下查询如果是一个2个关系
SELECT cat_id, name, (SELECT name FROM categories WHERE cat_id = a.parent_id) parent_name FROM categories a
答案 2 :(得分:0)
使用自我加入
SELECT p.cat_id, p.name, c.cat_id, c.name
FROM tbl_category p
INNER JOIN tbl_category c ON p.cat_id = c.parent_cat_id
然后用PHP操作结果数组以表格形式显示