Last active
February 27, 2024 01:48
-
-
Save mmousawy/654227deb569497205a944e517878aa9 to your computer and use it in GitHub Desktop.
Recursive SQL SELECT, UPDATE and DELETE with recursive CTE in MariaDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- SELECT | |
WITH recursive custom_cte AS | |
( SELECT | |
* | |
FROM | |
target_table | |
WHERE | |
target_table.id = "value" | |
UNION ALL | |
SELECT | |
a.* | |
FROM | |
target_table a | |
INNER JOIN | |
custom_cte b | |
ON | |
a.parent = b.id | |
) | |
SELECT | |
* | |
FROM | |
custom_cte | |
-- UPDATE | |
UPDATE | |
target_table AS table_alias | |
JOIN | |
( SELECT | |
* | |
FROM | |
( WITH recursive custom_cte AS | |
( SELECT | |
* | |
FROM | |
target_table | |
WHERE | |
target_table.id = "value" | |
UNION ALL | |
SELECT | |
a.* | |
FROM | |
target_table a | |
INNER JOIN | |
custom_cte b | |
ON | |
a.parent = b.id | |
) | |
SELECT | |
* | |
FROM | |
custom_cte | |
) AS x | |
) AS to_update | |
ON | |
table_alias.id = to_update.id | |
SET | |
table_alias.column = value | |
-- DELETE | |
DELETE table_alias FROM | |
target_table AS table_alias | |
JOIN | |
( SELECT | |
* | |
FROM | |
( WITH recursive custom_cte AS | |
( SELECT | |
* | |
FROM | |
target_table | |
WHERE | |
target_table.id = "value" | |
UNION ALL | |
SELECT | |
a.* | |
FROM | |
target_table a | |
INNER JOIN | |
custom_cte b | |
ON | |
a.parent = b.id | |
) | |
SELECT | |
* | |
FROM | |
custom_cte | |
) AS x | |
) AS to_update | |
ON | |
table_alias.id = to_update.id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment