pecee-pixie icon indicating copy to clipboard operation
pecee-pixie copied to clipboard

CTE / WITH RECURSIVE queries

Open TCB13 opened this issue 2 years ago • 0 comments

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.

TCB13 avatar Mar 20 '23 18:03 TCB13