2017-05-30 137 views
1

我有2个表格表示父子关系。根据表B记录从一个表中选择记录

父ID具有T.

这个父ID的下一个状态

enter image description here

select Child_id from table B where parent_id ='2'; 

的孩子记录总数是7。

以及这7条记录中,其中一条是3条子记录的父条。

我需要一些帮助来编写一个查询,它应该返回给定parent_id的所有子记录 ,这样子例子中的子记录总数将是(7-1)+ 3 = 9;

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'); 
+0

我删除了不兼容的数据库标签。 –

回答

0

您可以使用UNION查询合并两个水平(假设只有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' 
相关问题