获取多级计数
问题描述:
我试图让下线(refferals用户带来的)存储在数据库中的每个用户,如该人数:获取多级计数
------------------------------------
+ UserID + refferedby
------------------------------------
l 23 l 80
l 25 l 23
l 36 l 25
l 75 l 36
l 98 l 75
l 24 l 98
l 209 l 24
25带来的总转诊应该是:23 80,36,75,98,24,204
Pseudode:
function getalldownlines(){
// Get all users id and store in array
// loop through the array to get each users total downlines by calling function get_all()
}
function get_all(){
// get all users downline and downlines brought by user to the last user
// it should keep count each and every one of them
return $count;
}
什么是去了解它的最佳方式?
答
这里有几个选项。
第一个也很明显的是在PHP中创建一个递归函数,该函数返回一个用户的引用,然后再与他们每个人调用自己。
另一种选择是直接在SQL中进行。
MySQL例如支持递归,但其他一些RDBMS不支持。我不确定标准SQL是否支持递归语法。
更新:似乎我错了。 MySQL不支持递归查询; PostgreSQL,Firebird和MS Sql Server等等。
以下伪代码需要完成。我的PHP福是有点生疏:
function getalldownlines()
{
$sqlcmd = "SELECT UserID FROM table";
// fill array $arr with data from SQL
foreach ($id in $arr)
{
$count = get_all($id);
$numreferreds[$id] = $count;
}
}
function get_all($id)
{
$sqlcmd = "SELECT referredby FROM table WHERE UserId='$id'";
$count = 0;
// fill array $arr with data from SQL
foreach ($referred in $arr)
{
$count += get_all($referred);
}
return $count;
}
你想返回总数,实际记录? – BenM 2013-02-09 15:41:07
您使用的是什么数据库引擎? – 2013-02-09 15:56:29
我使用mysql数据库 – Udo 2013-02-09 16:00:52