Create a documents table:
CREATE table documents (objectid char(16), objectname char(80))
INSERT into documents (objectid, objectname)
values ('456', 'Test document'), ('123', 'Folder'), ('121', 'Upper folder'), ('120', 'Parent')
Create a relationships table:
CREATE table relationships (objectid char(16), parent char(16))
INSERT into relationships (objectid, parent)
values ('121','120'), ('123', '121'), ('456','123')
I am trying to use a SQL query to return the top relationship of each document like so:
objectid | topcontainer
—— | ——
120 | 120
121 | 120
123 | 120
456 | 120
I tried to use the following query, but it is not working. Not sure why but it terminates.
WITH c AS
(
SELECT d.objectid, r.parent, r.parent AS topcontainer
FROM documents d
JOIN relationships r ON d.objectid = r.objectid
UNION ALL
SELECT
t.objectid, t.parent, c.topcontainer
FROM
relationships AS t
JOIN c ON t.parent = c.parent
)
SELECT objectid, topcontainer
FROM c
ORDER BY c.objectid
0