1
1
WITH RECURSIVE TransferPaths AS (
2
- -- Base case: Start with the person with one of the emails as the source
2
+ -- Base case: Start with transfers FROM George
3
3
SELECT p1 .id AS start_id, p2 .id AS end_id, [(a1 .owner , a2 .owner , t .amount )] AS path ,
4
4
1 AS depth
5
5
FROM Person p1
6
6
JOIN Account a1 ON p1 .id = a1 .owner
7
- JOIN Transfer t ON a1 .owner = t .source OR a1 . owner = t . target
8
- JOIN Account a2 ON ( t . source = a2 . owner OR t . target = a2 .owner ) AND a2 . owner != a1 . owner
7
+ JOIN Transfer t ON a1 .owner = t .source -- Only FROM source
8
+ JOIN Account a2 ON t . target = a2 .owner -- Only TO target
9
9
JOIN Person p2 ON a2 .owner = p2 .id
10
- WHERE p1 .
email = ' [email protected] '
10
+ WHERE p1 .name = ' George '
11
11
12
12
UNION ALL
13
13
14
- -- Recursive case: Traverse up to N relationships deep
14
+ -- Recursive case: Follow only outgoing transfers
15
15
SELECT tp .start_id , p2 .id AS end_id, list_append(tp .path , (a1 .owner , a2 .owner , t .amount )), tp .depth + 1 AS depth
16
16
FROM TransferPaths tp
17
17
JOIN Account a1 ON tp .end_id = a1 .owner
18
- JOIN Transfer t ON a1 .owner = t .source OR a1 . owner = t . target
19
- JOIN Account a2 ON ( t . source = a2 . owner OR t . target = a2 .owner ) AND a2 . owner != a1 . owner
18
+ JOIN Transfer t ON a1 .owner = t .source -- Only FROM source
19
+ JOIN Account a2 ON t . target = a2 .owner -- Only TO target
20
20
JOIN Person p2 ON a2 .owner = p2 .id
21
21
WHERE tp .depth < 5
22
22
)
23
- -- Select the paths where the end person has the target email
24
23
SELECT start_id, end_id, path , depth
25
24
FROM TransferPaths, Person p
26
- WHERE end_id
= p .
id and p .
email = ' [email protected] '
25
+ WHERE end_id = p .id AND p .name = ' Edward '
27
26
ORDER BY depth
28
27
LIMIT 1 ;
0 commit comments