php - 查询中的递归求和

标签 php mysql recursion

我有一个表,其中的数据使用邻接表分层存储,如下例所示

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

And a table where I keep values for these accounts

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

I made a function which returns all child account given a parent account:

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

我想做的是一个函数,它不仅返回子帐户,还返回所有值的总和,包括每个结果的子帐户。例如

getChildrenAccount(4)

将返回具有以下语法的数组

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

And

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) ';
....
}

关于php - 查询中的递归求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10004715/

相关文章:

haskell - 使用 Haskell 循环遍历一组函数

python - 为什么我的递归函数更新列表(计算 n 的斐波那契)

php - 如何从另一个表进行内连接并按特定行值排序?

php - 如果执行查询则显示查询结果

mysql - 选择“计数”,然后选择“排序依据”

Java Mysql更新语句

c++ - 递归函数引起的栈溢出

php - curl 多次和返回转移

php - 具有多个 GROUP BY 的 MySQL 查询 - 如何在 HTML 表中将一组设为列标题,一组设为行标题?

javascript - MySQL 用 PASSWORD() 插入设置