簡體   English   中英

查詢中的遞歸求和

[英]Recursive sum in query

我有一個表,其中使用鄰接列表分層存儲數據,如下例所示

id     account parent
1      root    null
2      a1      1
3      b1      1
4      a2      2
5      a3      4
6      a4      2
7      b2      3

還有一張表,我在其中保存這些帳戶的值

id_account    value
2             10
2             10
4             20
5             30
6             10 

我創建了一個 function,它返回給定父帳戶的所有子帳戶:

function getChildrenAccount($parent_id)
  {
    $query = "SELECT id, account FROM accounts WHERE parent='{$parent_id}' ORDER BY account";
    $result = mysql_query($query) or die(mysql_error());
    while($r[]=mysql_fetch_assoc($result));
    return $r;
  }

我想要做的是一個 function,它不僅返回子帳戶,還返回所有值的總和,包括每個結果的子項。 例如

getChildrenAccount(4)

將返回具有以下語法的數組

array(1) { 
  [0]=> array(3) { 
     ["id"]=> 5
     ["account"]=> "a3"
     ["sum"]=> 50 //a2 + a3
}

getChildrenAccount(2)
array(2) { 
  [0]=> array(3) { 
     ["id"]=> 4
     ["account"]=> "a2"
     ["sum"]=> 70 //a1 + a2 + a3
  [1]=> array(3) { 
     ["id"]=> 6
     ["account"]=> "a4"
     ["sum"]=> 30 //a1 + a4
}

我想我必須在我的 while 語句中使用某種遞歸,但我有點困惑。 你能幫我嗎?

謝謝

function getChildrenAccount($accountID){

   $query = ' SELECT id,account,sum(value) as `SUM`
    FROM accounts,accountsValues
    WHERE accounts.id = accountsValues.id_accounts
    AND id = $accountID 
    OR id IN (SELECT id FROM accounts where parent = $accountID) ';
....
}

您需要遍歷結果,然后為每個 id 調用 getChildrenAccount 獲取其父 id。

我找到了一個 function,它可以根據需要獲取結果,而無需遞歸查詢。

$nodeList = array();
$tree     = array();
$query = mysql_query("SELECT A.guid, A.name, A.parent_guid, SUM( S.value_num ) /100 AS suma FROM accounts AS A
    LEFT JOIN splits AS S ON S.account_guid = A.guid GROUP BY A.guid ORDER BY A.name");
while($row = mysql_fetch_assoc($query))
  $nodeList[$row['guid']] = array_merge($row, array('children' => array()));
mysql_free_result($query);

foreach ($nodeList as $nodeId => &$node) {
  if (!$node['parent_guid'] || !array_key_exists($node['parent_guid'], $nodeList))
    $tree[] = &$node;
  else 
    $nodeList[$node['parent_guid']]['children'][] = &$node;
}
unset($node);
unset($nodeList);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM