Sql 根据表B记录从一个表中选择记录

Sql 根据表B记录从一个表中选择记录,sql,recursion,nested,Sql,Recursion,Nested,我有两个代表父子关系的表 父Id的状态为T 此父id下的子记录总数为7 在这7条记录中,有一条是3个子记录的父记录 我需要一些帮助来编写一个查询,该查询将返回给定父id的所有子记录 因此,在这种情况下,子记录的总数为(7-1)+3=9 您可以使用UNIONquery合并两个级别(假设只有两个级别),例如: 您可以使用UNIONquery合并两个级别(假设只有两个级别),例如: 我删除了不兼容的数据库标记。我删除了不兼容的数据库标记。 select Child_id from table B w

我有两个代表父子关系的表

父Id的状态为T

此父id下的子记录总数为7

在这7条记录中,有一条是3个子记录的父记录

我需要一些帮助来编写一个查询,该查询将返回给定父id的所有子记录 因此,在这种情况下,子记录的总数为(7-1)+3=9


您可以使用
UNION
query合并两个级别(假设只有两个级别),例如:


您可以使用
UNION
query合并两个级别(假设只有两个级别),例如:


我删除了不兼容的数据库标记。我删除了不兼容的数据库标记。
select Child_id from table B where parent_id ='2';
here is what I have tried already.
--this gives me the 7 child records
select distinct Child_id from table B 
where parent_id in(
select parent_id from Table A where status = 'T' 
and A.parent_id = B.parent_id
and A.parent_id ='2');
SELECT b.child_id
FROM tableB b JOIN tableA a ON b.parent_id = a.parent_id
WHERE a.status = 'T'

UNION

SELECT b.child_id
FROM tableB b JOIN tableB b1 ON b.parent_id = b1.child_id
JOIN tableA a ON b1.parent_id = a.parent_id
WHERE a.status = 'T'