我有一个层次结构的数据库表,其成员类似于上述带有父母和孩子的数组(一个mlm结构/树)。 表名是成员,表中的字段是上述数组中的元素(用户ID,引用ID,名称,用户名)。 如何计算一个用户名的所有子代?让我们以有孩子的用户ID 5和有孩子的孩子ID为例。 我希望一个sql代码为所有儿童和儿童儿童的用户ID计数。 谢谢!
Array
(
[0] => Array
(
[userid] => 3
[refferenceid] => 4
[name] => Bandil
[surname] => Kazim
)
[1] => Array
(
[userid] => 1
[refferenceid] => 2
[name] => Zarki
[surname] => Andrew
)
[2] => Array
(
[userid] => 5
[refferenceid] => 1
[name] => Mirko
[surname] => Paul
)
[3] => Array
(
[userid] => 2390189598
[refferenceid] => 5
[name] => Matias
[surname] => Clark
)
[4] => Array
(
[userid] => 4
[refferenceid] =>
[name] => Duncan
[surname] => Christoph
)
[5] => Array
(
[userid] => 2
[refferenceid] => 3
[name] => Zar
[surname] => Jamal
)
[6] => Array
(
[userid] => 123123
[refferenceid] => 5
[name] => Victor
[surname] => Dobrinski
)
[7] => Array
(
[userid] => 9
[refferenceid] => 2390189598
[name] => Slav
[surname] => Jorgasen
)
[8] => Array
(
[userid] => 4057926110
[refferenceid] => 5
[name] => Joseph
[surname] => Vladinski
)
[9] => Array
(
[userid] => 10
[refferenceid] => 2390189598
[name] => Jala
[surname] => David
)
[10] => Array
(
[userid] => 7568954902
[refferenceid] => 4057926110
[name] => ohn
[surname] => macaron
)
)
答案 0 :(得分:0)
如果REFFERENCEID是父亲的ID,这是一种方式
SELECT REFFERENCEID, COUNT(*)
FROM
(SELECT USERID, REFFERENCEID FROM MEMBERS
WHERE REFFERENCEID IS NOT NULL
UNION
SELECT B.USERID AS USERID, A.REFFERENCEID AS REFFERENCEID
FROM MEMBERS A
LEFT JOIN MEMBERS B
ON A.USERID=B.REFFERENCEID
WHERE B.USERID IS NOT NULL AND A.REFFERENCEID IS NOT NULL) TOT
GROUP BY REFFERENCEID;
结果是每个REFFERENCEID的儿子和侄子的数量;如果您想通过联合使用的两个集合上的REFFERENCEID来知道儿子的数目和侄子的数目。