如何为下面的问题编写sql查询?
我有一个带有如何为下面的问题编写sql查询?,sql,Sql,我有一个带有parentId和childId列的表: Parent id | ChildId ----------+--------- 0 | 1 1 | 2 2 | 3 0 | 4 Parent id=0表示此子项没有父项 如果我搜索子Id=4,它应该返回4,因为4没有父项 如果我搜索子Id=2,则应返回1,因为2具有父1 如果我搜索子Id=3,则应返回1,因为3有父2,2有父1 同样适用于 chi
parentId
和childId
列的表:
Parent id | ChildId
----------+---------
0 | 1
1 | 2
2 | 3
0 | 4
Parent id=0
表示此子项没有父项
- 如果我搜索
,它应该返回4,因为4没有父项子Id=4
- 如果我搜索
,则应返回1,因为2具有父1子Id=2
- 如果我搜索
,则应返回1,因为3有父2,2有父1子Id=3
->0childI=4
->1childI=2
->1childI=3
选择不同的按根连接childid根--,Parentid,childid
从t
从ChildId=XXX开始
按先前的Parentid=ChildId连接
我删除了不一致的数据库标记。请仅使用您真正使用的数据库进行标记。您似乎希望任何非根节点使用根节点,而根节点使用零。寻根是一个已经被问了很多次的问题。例如,谷歌“sql查找叶的根”。当rootid=childid,然后0 else childid end语句时,返回零只是一个简单的情况。您使用的是什么数据库?
--drop table parent_child;
create table parent_child (parent_id number(2),child_id number(2));
insert into parent_child values(0,1);
insert into parent_child values(1,2);
insert into parent_child values(2,3);
insert into parent_child values(0,4);
select p.*,sys_connect_by_path(parent_id,'--->') from parent_child p
start with child_id =2
connect by prior parent_id=child_id;