2016-02-24 38 views
1

我有兩個表:類別和對象。類別可以有一個或多個孩子。這些孩子可以有自己的孩子。所以,層次結構是無限的。一個孩子只能有一個父母。父類別是parent_id爲NULL的類別。類別具有對象(一對多關係)。如何計算父類別及其後代中的項目?

的樣本數據:

分類表

id name  parent_id  
1 Sports  NULL 
2 Home  NULL 
3 Fashion NULL 
4 Cycling 1 
5 Football 1 
6 Bath  2 
7 Bedroom 2 
8 Lighting 7 

假設數量類別中的對象是這樣的:

name  COUNT(object) 
Sports  5 
Home  3 
Fashion 4 
Cycling 2 
Football 3 
Bath  2 
Bedroom 1 
Lighting 3 

我需要得到僅爲父對象的數量包括使用純MySql或MySql和PHP在其後代中的對象計數。

這是我要找的結果。

Sports  5 + 2(for Cycling)+3(for Football) = 10 
Home  3+2(Bath)+1(Bedroom)+3(Lighting)= 9 
Fashion 4 

我知道嵌套集,但不能改變當前的數據庫結構。

回答

0

下面的PHP代碼就可以解決這個問題,可能有一個更好的答案,但什麼我現在告訴

<?php 
try{ 
    $conn = new PDO('mysql:host=localhost;dbname=test', 'root', 'root'); 
    $stm = $conn->prepare('select tem.id, tem.num, c.name, c.parent_id from category c inner join (SELECT c.id ,count(c.id) as num FROM `category` c left join object o on o.category = c.id 
group by c.id) tem on c.id = tem.id'); 
    $stm->execute(); 
    $result = $stm->fetchAll(PDO::FETCH_OBJ); 
    $temp = array(); 
    foreach($result as $row){ 
     $temp[$row->id] = $row; 
    } 


    $pre_final = moh($temp); 
    $final = array(); 
    foreach ($pre_final as $row){ 
      if(!$row->parent_id){ 
       $final[] = $row; 
      } 
    } 

    print_r($final); 
} 
catch(PDOException $e){ 
    print "Error!: " . $e->getMessage() . "<br/>"; 
    die(); 
} 

function moh($arr){ 
    $flag = true; 
    foreach($arr as $row){ 
     if(!$row->parent_id){ 

     } else{ 
      $arr[$row->parent_id]->num += $row->num; 
      $row->num = 0; 
     } 
    } 



    foreach($arr as $row){ 
     if(!$row->parent_id){ 

     } else{ 
      if($row->num != 0){ 
       $flag = false; 
       break; 
      } 
     } 
    } 

    if($flag){ 
     return $arr; 
    } else{ 
     return moh($arr); 
    } 


} 
相關問題