获得root父母

时间:2011-12-12 19:58:28

标签: mysql hierarchical

+--------+---------+-----------+
|   id   | title   | parent_id |
+--------+---------+-----------+
|    1   | Lvl-1   |   null    |
+--------+---------+-----------+
|    2   | Lvl-2   |   null    |
+--------+---------+-----------+
|    3   | Lvl-11  |     1     |
+--------+---------+-----------+
|    4   | Lvl-12  |     1     |
+--------+---------+-----------+
|    5   | Lvl-121 |     4     |
+--------+---------+-----------+

我如何实际获得每行的根父母
例如,id 5行的父级{(1}}为父级,id 4的父级为id 4,因此id 1的root ID为id 5
我对如何做到这一点没有任何想法,有没有办法通过只使用1个查询来解决这个问题

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:2)

这是一个简短的查询,按照您的要求进行操作,假设您的表名为SELECT f.id, f.title FROM ( SELECT @id AS _id, (SELECT @id := parent_id FROM foo WHERE id = _id) FROM (SELECT @id := <id>) tmp1 JOIN foo ON @id IS NOT NULL ) tmp2 JOIN foo f ON tmp2._id = f.id WHERE f.parent_id IS NULL ,并且您想知道 Dim rs As DAO.Recordset Set rs = Me.RecordsetClone rs.FindFirst "[MyPK]=" & Me!cmbFindByPK If Not rs.NoMatch Then If Me.Dirty Then Me.Dirty = False End If Me.Bookmark = rs.Bookmark End If Set rs = Nothing 的根:

var forwarder = new BufferBlock<SomeType>();
forwarder.LinkTo(target1, item => matchesTarget1(item));
forwarder.LinkTo(target2, item => matchesTarget2(item));
forwarder.LinkTo(DataflowBlock.NullTarget<SomeType>(), item => !matchesTarget1(item) && !matchesTarget2(item));

答案 2 :(得分:0)

如果您的树形结构超过两层深度,那么您正在搜索modified preorder tree traversal