Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CTE / WITH RECURSIVE queries #151

Open
TCB13 opened this issue Mar 20, 2023 · 0 comments
Open

CTE / WITH RECURSIVE queries #151

TCB13 opened this issue Mar 20, 2023 · 0 comments

Comments

@TCB13
Copy link
Contributor

TCB13 commented Mar 20, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant