我有2个表,应该将文件夹结构显示为树。所以每个文件夹都有一个id和一个名字。如果它是其他文件夹的子文件夹,则它具有如下父ID:
表格文件夹:
Folderid name
11111112 xxy
11111113 yyy
11111114 yxy
...
表格结构
folderid parentid ...
11111112 NULL
11111113 11111112
11111114 11111113
我现在的问题是如何检查mysql查询文件夹是否是另一个文件夹的子文件夹(但它不能是父文件夹)
例如:
如何检查文件夹11111114
是否在11111112
???
我会检查递归,但问题是计数是未知的,所以我现在经常做这个步骤。
也许你可以帮助我?
答案 0 :(得分:1)
MySQL文档有一些关于存储分层数据的指南:Managing Hierarchical Data in MySQL。
答案 1 :(得分:0)
让我们从这个结构开始(让名字表folders
)。也许你可以把这个案子改成你的。
{
id => 'int',
label => 'string', # folder name
parent => 'int' # reference to folder parent (only one)
# folder has unlimited number of children
}
更多伪代码
subtree_ids = select_subtree_ids (root)
if id_folder in subtree_ids
bingo! id_folder is subfolder of root
你需要的是写select_subtree_ids()
你不能在一个查询中这样做(我错了吗?)
类似的东西(伪代码,再次)
select_subtree (root) {
ids = (root); # result array contains initial id (for convenience)
while (TRUE) { # depth is unknown
# array of folder ids from next level only
my new_ids = sql_select_array ("SELECT id FROM folders WHERE parent IN (ids) AND id NOT IN (ids)");
break if no_new_ids;
ids = ids + new_ids;
}
return ids;
}