0

我有一个包含多达 3 级子类别的类别树,如下所示:

家居用品->客厅->沙发->双座

家居产品->客厅->沙发->三人座

houseproducts->客厅->沙发->fourseats

因此,对于每个子级别,我都会根据母亲的类别 ID 进行 SELECT。这是在 PHP 循环中完成的,如下面的代码,但我想它可以在一个 Mysql 查询中完成,以获得更好的性能。我尝试了不同的 JOINS,但发现它真的很困难。任何建议将不胜感激。

function build_category_tree() 
{
    $cat = array();

    // main category loop
    $r1 = mysql_query("SELECT cat_id,cat_name FROM categories WHERE cat_mother=0 OR cat_mother='' ORDER BY cat_name");  
    while ($row=mysql_fetch_assoc($r1)) 
    {
        $cat[$row['cat_id']] = $row['cat_name'];        

        // check for subcategories
        $r2 = mysql_query("SELECT cat_id,cat_name FROM categories WHERE cat_mother='".$row['cat_id']."'");    
        while ($subrow=mysql_fetch_assoc($r2)) 
        {
            $cat[$subrow['cat_id']] = ' - '.$subrow['cat_name'];                

            // check if there is subcats for the current subcategory
            $r3 = mysql_query("SELECT cat_id,cat_name FROM categories WHERE cat_mother='".$subrow['cat_id']."'");    
            while ($subrow2=mysql_fetch_assoc($r3)) 
            {
                $cat[$subrow2['cat_id']] = ' -- '.$subrow2['cat_name'];     

                // check if there is subcats for the current subcategory 
                $r4 = mysql_query("SELECT cat_id,cat_name FROM categories WHERE cat_mother='".$subrow2['cat_id']."'");    
                while ($subrow3=mysql_fetch_assoc($r4)) 
                {
                    $cat[$subrow3['cat_id']] = ' --- '.$subrow3['cat_name'];
                }                   
            }
        }           
    } 
    return $cat;
}
4

2 回答 2

0

尝试这个:

SELECT l1.cat_id AS l1_cat_id
    ,l1.cat_name AS l1_cat_name
    ,l2.cat_id AS l2_cat_id
    ,l2.cat_name AS l2_cat_name
    ,l3.cat_id AS l3_cat_id
    ,l3.cat_name AS l3_cat_name
    ,l4.cat_id AS l4_cat_id
    ,l4.cat_name AS l4_cat_name
FROM categories AS l1
JOIN categories AS l2
  ON l2.cat_mother = l1.cat_id
JOIN categories AS l3
  ON l3.cat_mother = l2.cat_id
JOIN categories AS l4
  ON l4.cat_mother = l3.cat_id
WHERE l1.cat_mother=0 OR l1.cat_mother='' 
ORDER BY l1_cat_name, l2_cat_name, l3_cat_name, l4_cat_name
于 2013-10-13T19:22:19.183 回答
0

我会将您的整个表格读入一个数组并通过母亲的键将该数组分段

于 2013-10-13T18:41:48.367 回答