2

我为我的项目工作分层类别和产品表。

类别表结构:

ID - 父母 - 职务

1 - 0 - 电脑

1 - 0 - 电话

...

第 25107 行的类别表计数。

产品表结构

ID - 猫 - 标题

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,9246701,905218,4,4 ,90516,905111951195119511905119511951195181195119511951811905119518119051891981981981981981818 ,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)

这个查询很慢...请帮助我。

4

2 回答 2

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

看看它在SQLFIDDLE上是如何工作的

要列出所有层次结构级别,请编写如下代码:

// 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
}

然后在您的代码中为您想要获取儿童的每个类别调用此函数

于 2012-09-23T12:18:15.697 回答
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

 ?>`
于 2013-07-13T19:35:14.027 回答