DB2 中的递归查询以获取链中的所有项目 [英] Recursive query in DB2 to get all items in the chain

查看:18
本文介绍了DB2 中的递归查询以获取链中的所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to retrieve all clients linked via loans by giving only one as input. Example I have a table data as

表格

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 再次有 5 作为贷款 ID.

If I have given only input as CLIENT_ID=7 then the query has to select all the columns from above table except last two column because client_id 7 has 1,2 LOAN_ID and in 1 the CLIENT_ID 8 has loan_id=4 and in this loan CLIENT_id 9 has again 5 as loan_id.

我们可以为此编写一个不使用 DB2 存储过程的 sql 查询吗?

can we write a sql query for this without stored procedure in DB2 ?

推荐答案

以下是您使用递归 CTE 查询的问题的答案:

Here is the answer to your question using recursive CTE query:

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 以便于理解.

I have left distance inside the query to make it easier to understand.

这篇关于DB2 中的递归查询以获取链中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆