I have to come up with another question, which costs me already hours, and I am not able to solve it. I need to write a recursive Query in PostgreSQL (for univercity). I have a relation called "basedOn" where machines are basedOn other (older) versions like:
CREATE TABLE BasedON(
fromID integer,
fromSize numeric,
toID integer,
toSize numeric,
...
);
I need know to find all transitive versions which base on others (like if A bases on B, and B on C, A bases on C) using a recursive Query. My Problem now is, that I have to solve this also for Cycles like "A bases on B, B on C, and C on A", where my query loops infinite. Thats what my query looks like now:
WITH RECURSIVE tmp(fromID, fromSize, toID, toSize,c) AS (
SELECT fromID, fromSize, toID, toSize, 0 FROM BasedOn
WHERE toID= 0 AND toSize= 2.0 --start
UNION
SELECT b.fromID, b.fromSize, t.toID,t.toSIze, c+1 AS steps
FROM BasedOn b JOIN tmp t ON
t.fromID= b.toID AND t.fromSize= b.toSize
)SELECT * FROM tmp;
"c" is just use to "count" the recursive steps. It works thine for non-cyclic data. But if I insert an cycle into the data it loops infinite. Has anyone a tip, how to avoid this? Thanks in advance, Lukas
SampleData:
INSERT INTO BasedOn VALUES
(7000, 1.28, 7003, 2.52),
(7003, 2.52, 7006, 0.98), --cycle
(7006, 0.98, 7009, 4.18),
(7006, 0.98, 7003, 2.52), --cycle
(7009, 4.18, 7015, 1.33),
(7009, 4.18, 0, 2.00);
Expected output:
fromID, fromSize, toID, toSize,stepcount
7009 4.18 0 2.00 0
7006 0.98 0 2.00 1
7003 2.52 0 2.00 2
7000 1.28 0 2.00 3