如何检查类别是否有父级或子级?

tv6aics1  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(363)

我有这样的分类表。。。

Id ParentId Name
1  0        a
2  1        a1
3  2        a2

如何检查a2是否有祖父母或孙子?在sql中?

4uqofj5v

4uqofj5v1#

找到祖父母那一排 a2 你可以做:

select c.*
from t a
join t b on b.id = a.parentid
join t c on c.id = b.parentid
where a.name = 'a2'

找到一排排的孙子 a2 你可以做:

select c.*
from t a
join t b on b.parentid = a.id
join t c on c.parentid = b.id
where a.name = 'a2'
ogq8wdun

ogq8wdun2#

您可以使用递归cte方法检查父级或子级:

with r_cte as (
     select t.id, t.parentid, t.name
     from table t
     where t.name = 'a2'
     union all
     select tm.id, tm.parentid, tm.name
     from table tm inner join
          r_cte r
          on r.parentid = tm.id
)
select rc.*
from r_cte rc;

相关问题