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

时间:2014-09-21 20:58:07

标签: sql db2 recursive-query

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

TABLEA

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,而在1中CLIENT_ID 8有loan_id = 4并且在此贷款CLIENT_id 9再次作为loan_id 5。

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

1 个答案:

答案 0 :(得分:2)

以下是使用递归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留在查询中,以便更容易理解。