如何为下面的问题编写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
表示此子项没有父项

  • 如果我搜索
    子Id=4
    ,它应该返回4,因为4没有父项
  • 如果我搜索
    子Id=2
    ,则应返回1,因为2具有父1
  • 如果我搜索
    子Id=3
    ,则应返回1,因为3有父2,2有父1
同样适用于

  • childI=4
    ->0
  • childI=2
    ->1
  • childI=3
    ->1

在oracle数据库中,connect\u by\u root函数可以很好地实现这一点,只需将xxx替换为任何ChildId值即可

选择不同的按根连接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;