在 PHP 中使用查询而不是循环构建 Mysql 表树


Building a Mysql table-tree using query instead of loops in PHP

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

家居用品->客厅->沙发->两人座

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

家居用品->客厅->沙发->四人座

因此,对于每个子级别,我都会根据母亲类别ID进行选择。这是在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;
}

我会将您的整个表读入一个数组,并按母亲的键对该数组进行分段

试试这个:

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