簡體   English   中英

根據表B記錄從一個表中選擇記錄

[英]select records from one table based on table B records

我有2個表代表父子關系的表。

Parent Id的狀態為T.

在此輸入圖像描述

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

此父ID下的子記錄總數為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');

您可以使用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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM