返回与父项相关的所有子记录

时间:2014-03-25 18:58:24

标签: sql

我有一个包含以下字段的ACCOUNT表:Acct#,Name

和子表CFALTN,包含字段:cfseq,cfaal1,cfacc#

我想在以下示例中查询并链接主要记录到所有子记录:

TABLE1
Acct#, Name
2244,  Joe 
1890,  Jack
0223,  Sam
9898,  Mary

TABLE2
cfseq, cfaal1, cfacc#
1, Joe and bens farm, 2244
2, POD mary and ben,  2244
1, POD Jay Williams,  1890
1, POD Ronnie future farm, 0223
2, for raising goats, 0223
1, OR James Russell, 9898

我想查询在孩子中找到POD的位置,但不仅仅返回有POD的子记录,而是两个子记录。

SELECT T1.acct#, T1.name, T2.cfseq, T2.cfaal1, T2.cfacc#
FROM data.table1 T1
    JOIN  data.table2 T2 WHERE T1.acct# = T2.cfacc# 
AND T2.cfaal1 like '%POD%'

DESIRED RESULTS:
2244, Joe, 1, Joe and bens farm, 2244
2244, Joe, 2, POD mary and ben,  2244
1890, Jack, 1, POD Jay Williams, 1890
0223, Sam, 1, POD Ronnie future trust, 0223
0223, Sam, 2, for education wing, 0223

1 个答案:

答案 0 :(得分:1)

SELECT T1.acct#, T1.name, T2.cfseq, T2.cfaal1, T2.cfacc#
FROM data.table1 T1
JOIN  data.table2 T2 ON T1.acct# = T2.cfacc# 
where
    T1.acct# in (select cfacc# from T2 where cfaal1 like '%POD%')