我为我的项目工作分层类别和产品表。
类别表结构:
ID - PARENT - TITLE
1 - 0 - 电脑
1 - 0 - 电话
...
第25107行的类别表计数。
产品表结构
ID - CAT - TITLE
1 - 1 - 产品名称在这里
我想要列表产品的当前类别和子类别。
echo $subcats = categoryChild(0);
产出为:64198,18355,18356,95623,90504,6118,90505,6117,90506,90507,6119,6120,90508,90509,90510,90511,6103,90512,90513,90514,90515,142686, 142688,142790,90516,6105,90517,90518,90519,90520,90521,91691,91692,92189,92190,92312,92313,95618,95619,95620,95621,95622,142684,142690,142692,142694,142696, 142698,142700,3596
我正在使用此输出MySQL IN语句。 最后生成这个SQL查询:
SELECT * FROM products WHERE cat IN (64198,18355,18356,95623,90504,6118,90505,6117,90506,90507,6119,6120,90508,90509,90510,90511,6103,90512,90513,90514,90515,142686,142688,142790,90516,6105,90517,90518,90519,90520,90521,91691,91692,92189,92190,92312,92313,95618,95619,95620,95621,95622,142684,142690,142692,142694,142696,142698,142700,3596)
这个查询很慢......请帮帮我。
答案 0 :(得分:2)
试试这个:
select p.id as id, p.title as title, c.title as category, c.id as catid
from products p JOIN
(select * from category where id = 1 OR parent = 1) c
on p.cat = c.id
的工作原理
列出所有层次结构级别,编写如下代码:
// return all childs of category with id $cat
function list_childs($cat){
// run above query and change (select * from category where id = 1 OR parent = 1)
// to (select * from category where parent = $cat) and return results
}
然后在你的代码中为你想要获得孩子的每个类别调用这个函数
答案 1 :(得分:0)
使用它将允许您为parent_id参数获取cat和sub cat。 它的嵌套,可以是css和html的样式。
`
<ul class="" id="">
<?php
function query($parent_id, $extension = null) { //function to run a query
$query = mysql_query ( "SELECT * FROM exe_categories WHERE parent_id=$parent_id");
return $query;
}
function has_child($query) { //This function checks if the menus has childs or not
$rows = mysql_num_rows ( $query );
if ($rows > 0) {
return true;
} else {
return false;
}
}
function fetch_menu($query) {
while ( $result = mysql_fetch_array ( $query ) ) {
$id = $result ['id'];
$title = $result ['title'];
$menu_link = $result ['menu_link'];
echo "<li><a href='{$menu_link}'><span>{$title}</span></a>";
if (has_child ( query ( $id ) )) {
echo "<div>";
echo '<ul role="menu" class="fofc">';
fetch_menu ( query ( $id ) );
echo "</ul>";
echo "</div>";
}
echo "</li>";
}
}
fetch_menu (query(1)); //call this function with 1 parent id
?>`