Skip to content

CTE / WITH RECURSIVE queries #151

@TCB13

Description

@TCB13

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions