一尘不染

DB2中的递归查询以获取链中的所有项目

sql

我必须通过仅输入一个作为输入来检索通过贷款链接的所有客户。示例我有一个表数据为

桌布

LOAN_ID    CLIENT_ID
1          7
1          8
2          7
4          8
4          9
4         10
5          9
5         11
13        2
14        3

如果我仅给出CLIENT_ID = 7作为输入,那么该查询必须选择上表中除最后两列以外的所有列,因为client_id 7具有1,2
LOAN_ID,在CLIENT_ID 8中具有loan_id = 4,在此贷款中CLIENT_id 9再次有5作为loan_id。

我们可以在没有DB2的存储过程的情况下为此编写SQL查询吗?


阅读 128

收藏
2021-05-05

共1个答案

一尘不染

这是使用递归CTE查询的问题答案:

WITH links AS
( SELECT 
    loan_id, 
    client_id as c1, 
    client_id as c2, 0 as distance 
  FROM 
    myTable 
  -- recursion 
  UNION ALL
  SELECT 
     t.loan_id, 
     l.c1 as c1, 
     tt.client_id as c2, 
     distance = distance + 1 
  FROM 
    links l INNER JOIN
    myTable t ON l.c2 = t.client_id
    AND l.loan_id != t.loan_id INNER JOIN
    myTable tt  ON t.loan_id = tt.loan_id 
     AND t.client_id != tt.client_id
 )
SELECT * FROM myTable t
WHERE EXISTS 
    (SELECT * FROM links 
     WHERE c2 = t.client_id and c1 = 7);

http://sqlfiddle.com/#!3/8394d/16

我已将distance查询保留在其中以使其更易于理解。

2021-05-05