如何编写 SQL 脚本来查找与原始 ID 关联的所有关系?

How do I write a SQL script to find all relationships tied to an original id?

例如:

我想传入税号以查找与此税号关联的所有帐户。这将是:

SELECT TAX_ID, ACCOUNT_NUMBER FROM CUSTOMER_RECORDS

然后我会得到所有帐户的列表。但是,每个账户也可能有其他关联的税号(共同借款人、担保人等)。所以我想获取返回的帐户,然后找到与它们关联的所有税号。然后,我需要重复这些步骤来查找与返回的所有新税号关联的所有帐户。

最终结果将是一个包含所有帐户和税号的列表 "relationship"。

我在想递归 CTE 是否适用于这种情况?然而,这有点超出了我在 SQL 的技能水平。如果有任何帮助,我将不胜感激。

请尝试以下操作:

with customer_records as
(
select 111 tax_id, 0 account_number from dual union
select 1 , 100 from dual union
select 1 , 200 from dual union
select 1 , 300 from dual union
select 1 , 400 from dual union
select 2 , 100 from dual union
select 3 , 202 from dual union
select 4 , 303 from dual union
select 5 , 400 from dual union
select 0 , 222 from dual 
)
SELECT c1.TAX_ID, c1.ACCOUNT_NUMBER 
FROM CUSTOMER_RECORDS c1
where 1=1
  and c1.tax_id = :tax_id
union
SELECT c2.TAX_ID, c2.ACCOUNT_NUMBER 
FROM CUSTOMER_RECORDS c1
, CUSTOMER_RECORDS c2
where 1=1
  and c1.tax_id = :tax_id
  and c1.tax_id <> c2.tax_id 
  and c1.account_number = c2.account_number
;

很确定你可以用 hierarchical query 做到这一点。请小心 - 如果您不小心,这些东西可能会离您而去,然后您会接到 DBA "why is query running for 6 days" 的电话。示例:

with base_data as
(
  select 1 as tax_id, 'A' as account_number from dual union all
  select 1 as tax_id, 'B' as account_number from dual union all
  select 2 as tax_id, 'A' as account_number from dual union all
  select 2 as tax_id, 'B' as account_number from dual union all
  select 2 as tax_id, 'C' as account_number from dual union all
  select 3 as tax_id, 'D' as account_number from dual union all
  select 3 as tax_id, 'E' as account_number from dual union all
  select 4 as tax_id, 'E' as account_number from dual union all
  select 4 as tax_id, 'F' as account_number from dual union all
  select 5 as tax_id, 'A' as account_number from dual union all
  select 5 as tax_id, 'F' as account_number from dual union all
  select 6 as tax_id, 'G' as account_number from dual union all
  select 7 as tax_id, 'H' as account_number from dual union all
  select 7 as tax_id, 'I' as account_number from dual union all
  select 8 as tax_id, 'I' as account_number from dual union all
  select 8 as tax_id, 'K' as account_number from dual
)

select distinct bd.*
from base_data bd
start with tax_id = :taxID
connect by nocycle (prior account_number = account_number or prior tax_id = tax_id)
--and level <= 10
order by 1, 2

如前所述,注释掉 "and level <= 10",这将 return 所有项目。可能想要取消注释并设置最大级别 - 本质上限制了查询看起来的兔子洞的深度。