这是使用递归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 tWHERe EXISTS (SELECt * FROM links WHERe c2 = t.client_id and c1 = 7);
http://sqlfiddle.com/#!3/8394d/16
我已将
distance查询保留在其中以使其更易于理解。



