Is it possible to write queries that include a recursive common table expression (CTE) for recursive operations?
Considering the following services table that has a tree structure of multiple items that can be children of others:
CREATE TABLE `services` (
`id` uuid NOT NULL,
`datecreated` datetime(6) DEFAULT NULL,
`parentid` uuid DEFAULT NULL
PRIMARY KEY (`id`) USING BTREE,
KEY `fk_services_parentid` (`parentid`),
CONSTRAINT `fk_services_parentid` FOREIGN KEY (`parentid`) REFERENCES `services` (`id`)
);
Now, if I want to find the root parent of any given service I can do a query like:
WITH RECURSIVE cte AS (
SELECT id, parentid
FROM services
WHERE id = 'given_id'
UNION ALL
SELECT s.id, s.parentid
FROM services s
JOIN cte ON s.id = cte.parentid
)
SELECT id, parentid
FROM cte
WHERE parentid IS NULL;
I tried to wrap the WITH RECURSIVE cte AS (... part in a select($qb->raw('WITH RECURSIVE cte AS (...')) but it didn't work. Is there any way to really place the CTE before the rest of the generated query?
Thank you.
Is it possible to write queries that include a recursive common table expression (CTE) for recursive operations?
Considering the following
servicestable that has a tree structure of multiple items that can be children of others:Now, if I want to find the root parent of any given
serviceI can do a query like:I tried to wrap the
WITH RECURSIVE cte AS (...part in aselect($qb->raw('WITH RECURSIVE cte AS (...'))but it didn't work. Is there any way to really place the CTE before the rest of the generated query?Thank you.