父母的sql孩子和孩子的孩子

时间:2020-06-26 11:04:48

标签: sql ms-access

parent_id 0类别1
parent_id 0类别2
parent_id 0类别3
parent_id 1类别4
parent_id 1类别5
parent_id 2类别6
parent_id 2类别7
parent_id 3类别8
parent_id 4类别9
parent_id 4类别10

我需要sql where语句以获取具有parent_id 0和parent_id parent_id 0的类别。在上表中,我将仅获得类别1-8。

预先感谢

1 个答案:

答案 0 :(得分:0)

假设id所引用的表中实际上有一个parentid,则可以在where子句中使用子查询来查找祖父母:

select t.*
from t
where t.parentid = 0 or
      (select t2.parentid
       from t as t2
       where t2.id = t.parentid and t2.parentid
      ) = 0;