MySQL - 获取层次结构中的顶级父 ID [英] MySQL - Getting the top-level parent id in a hierarchy
问题描述
这是我的表结构...
表格:position_hierarchy_level
id parent_position_id position_id
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
6 6 7
7 7 8
8 8 9
9 9 10
10 10 11
11 11 12
12 12 13
13 13 14
14 14 15
我获取某个position_id
的parent_position_id
的查询是:
My query for getting the parent_position_id
of a certain position_id
is:
select `parent_position_id` from `position_hierarchy_level` where position_id= 15;
但是我怎样才能获得某个 position_id
的最顶层父级?例如,position_id
15 的最顶层 parent_position_id
将是 1
.
But how can I get the top-most parent of a certain position_id
? For example, the top-most parent_position_id
of position_id
15 would be 1
.
是否有一种方便的方法可以使用单个查询获取此值?还是我需要在 PHP 中创建一个循环?
Is there a convenient way to get this value using a single query? Or do I need to create a loop in PHP?
推荐答案
除非有 15 个或更多联接,否则您的数据库结构不允许您这样做.您正在使用邻接表模型.尝试使用嵌套集模型
Your database structure wouldnt let you do it unless there are 15 or more joins. You are using Adjacency list model. Try using The nested set model
这里是一个例子 php
这篇关于MySQL - 获取层次结构中的顶级父 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!