我的问题是,我有一个由两列组成的表格。它描述了文件夹。第一列是父文件夹的
id
,第二列是子文件夹。然后,通过这张表我可以说出文件夹中的哪个文件夹X
。
但是我可以拥有文件夹 2 中的文件夹 3,而文件夹 2 又位于文件夹 1 中。 我正在寻找的是一种在一个 SQL 请求中从文件夹 ID 查找所有父文件夹的方法。
例如,从
ID = 3
,我的要求必须给我[1,2]
。
所以,过一段时间我就可以找到所有父文件夹,但如果该文件夹有 457 个父文件夹,那么仅一个文件夹就会很重!
以下请求请家长
id
:
$sql = "SELECT IDFolder1 FROM folder_has_folder WHERE IDFolder2='$this->id'";
但不知道有多少家长有文件夹。
你有想法做这个吗? 感谢您的帮助!
例如:
create table dbo.FOLDER (id_parent int, id_child int)
insert into dbo.FOLDER (id_parent, id_child) values (NULL,1), (1,2), (2,3)
with CTE as
(select id_parent, id_child
from dbo.FOLDER
where id_parent is null
union all
select f.id_parent, f.id_child
from dbo.FOLDER f
join CTE c on f.id_parent = c.id_child
)
select * from CTE
这可以在Sql Server中这样实现;
with CTE as
(select id_parent, id_child
from dbo.FOLDER
where id_child=3
union all
select f.id_parent, f.id_child
from dbo.FOLDER f
join CTE c on c.id_parent = f.id_child
)
select * from CTE
在 Oracle 中是这样的:
select a.*, connect_by_root id_parent as root, connect_by_isleaf as last_level
from folder a
start with id_child=3
connect by id_child= prior id_parent;
希望有帮助。