父 - 单个表中的子关系

时间:2013-03-21 08:48:12

标签: php mysql parent-child

我有一张如下表所示。

parentid   uid
10001      10001
10001      10002
10001      10003
10002      10004
10004      10005
10003      10006
10005      10007

我需要在此单个表中的行之间建立父子关系。

我需要以相反的顺序获取父级直到4级。例如,最后一条记录为 uid 10007 parentid为10005 。现在 uid 10005 的父母 10004 10004 的父母 10002 10002 的父母 10001

我正在使用MySQL,所以递归似乎是不可能的。我有哪些选项以及如何解决这个多层次问题。我使用PHP / MySQL。

先谢谢你们。

1 个答案:

答案 0 :(得分:2)

由于你有4级有限,你不应该需要递归(尽管能够使用例如MS SQL CTE是很方便的。)

类似的东西:

SELECT
  t4.uid as child, 
  --t3.uid as parent,
  --t2.uid as grand_parent,
  --t1.uid as great_grand_parent,
  t1.parentid as great_great_grand_parent
FROM
  your_table_name t1

  inner join your_table_name t2
  on t2.parentid = t1.uid

  inner join your_table_name t3
  on t3.parentid = t2.uid

  inner join your_table_name t4
  on t4.parentid = t3.uin

where 
  t4.uid = '10007' -- your start node.

如果您需要为多个节点执行此操作,则需要将其连接到选择起始节点的内容,或者将上述WHERE t4.uid = '10007'子句替换为WHERE t4.uid IN (SELECT DISTINCT uid FROM your_table_name)

这是徒手做的,所以为拼写错误道歉。

相关问题