How to select recursively in a child parent design situation (in MySQL)?
Let's take into consideration the following tables:
CREATE TABLE actions
(
id BIGINT(20) unsigned PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
user_id BIGINT(20) unsigned NOT NULL
);
CREATE TABLE recurring_actions
(
original_action_id BIGINT(20) unsigned NOT NULL,
recurring_action_id BIGINT(20) unsigned NOT NULL
);
The data in each table just for an example is as follows:
actions
id name user_id
1 fdfdk 3
2 43434 3
3 43334 5
4 sdkk 6
5 zz 7
6 ll 3
recurring_actions
original_action_id recurring_action_id
1 2
4 6
2 3
3 5
How can someone query and fetch all the chain of recurring action ids that lead to the last child with id 5 ?
Expected result should be [1, 2, 3, 5] (including 5 is ok)
I can solve this so far only by recursive querying by application code. Get the original action then if found, query again and so on. Recursive consecutive queries initiated by PHP/C# or whatever code used.
I want to do this instead in one recursive (or other solution) MySQL query
The answer should focus only on a query solution (if possible) and not in organizing the database in another way. I am aware of other possible database designs which are more suitable for child parent relationships (such as closure tables, nested sets etc).
mysql select query recursive
bumped to the homepage by Community♦ 24 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
add a comment |
Let's take into consideration the following tables:
CREATE TABLE actions
(
id BIGINT(20) unsigned PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
user_id BIGINT(20) unsigned NOT NULL
);
CREATE TABLE recurring_actions
(
original_action_id BIGINT(20) unsigned NOT NULL,
recurring_action_id BIGINT(20) unsigned NOT NULL
);
The data in each table just for an example is as follows:
actions
id name user_id
1 fdfdk 3
2 43434 3
3 43334 5
4 sdkk 6
5 zz 7
6 ll 3
recurring_actions
original_action_id recurring_action_id
1 2
4 6
2 3
3 5
How can someone query and fetch all the chain of recurring action ids that lead to the last child with id 5 ?
Expected result should be [1, 2, 3, 5] (including 5 is ok)
I can solve this so far only by recursive querying by application code. Get the original action then if found, query again and so on. Recursive consecutive queries initiated by PHP/C# or whatever code used.
I want to do this instead in one recursive (or other solution) MySQL query
The answer should focus only on a query solution (if possible) and not in organizing the database in another way. I am aware of other possible database designs which are more suitable for child parent relationships (such as closure tables, nested sets etc).
mysql select query recursive
bumped to the homepage by Community♦ 24 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
What version of MySQL are you using? I believe with 8.0 you can do what you want more easily: dev.mysql.com/doc/refman/8.0/en/with.html
– Willem Renzema
Jul 6 '18 at 13:19
Unfortunately it is version 5.7
– Kristi Jorgji
Jul 6 '18 at 13:21
Also, MariaDB 10.2 implemented such.
– Rick James
Jul 6 '18 at 13:31
add a comment |
Let's take into consideration the following tables:
CREATE TABLE actions
(
id BIGINT(20) unsigned PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
user_id BIGINT(20) unsigned NOT NULL
);
CREATE TABLE recurring_actions
(
original_action_id BIGINT(20) unsigned NOT NULL,
recurring_action_id BIGINT(20) unsigned NOT NULL
);
The data in each table just for an example is as follows:
actions
id name user_id
1 fdfdk 3
2 43434 3
3 43334 5
4 sdkk 6
5 zz 7
6 ll 3
recurring_actions
original_action_id recurring_action_id
1 2
4 6
2 3
3 5
How can someone query and fetch all the chain of recurring action ids that lead to the last child with id 5 ?
Expected result should be [1, 2, 3, 5] (including 5 is ok)
I can solve this so far only by recursive querying by application code. Get the original action then if found, query again and so on. Recursive consecutive queries initiated by PHP/C# or whatever code used.
I want to do this instead in one recursive (or other solution) MySQL query
The answer should focus only on a query solution (if possible) and not in organizing the database in another way. I am aware of other possible database designs which are more suitable for child parent relationships (such as closure tables, nested sets etc).
mysql select query recursive
Let's take into consideration the following tables:
CREATE TABLE actions
(
id BIGINT(20) unsigned PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
user_id BIGINT(20) unsigned NOT NULL
);
CREATE TABLE recurring_actions
(
original_action_id BIGINT(20) unsigned NOT NULL,
recurring_action_id BIGINT(20) unsigned NOT NULL
);
The data in each table just for an example is as follows:
actions
id name user_id
1 fdfdk 3
2 43434 3
3 43334 5
4 sdkk 6
5 zz 7
6 ll 3
recurring_actions
original_action_id recurring_action_id
1 2
4 6
2 3
3 5
How can someone query and fetch all the chain of recurring action ids that lead to the last child with id 5 ?
Expected result should be [1, 2, 3, 5] (including 5 is ok)
I can solve this so far only by recursive querying by application code. Get the original action then if found, query again and so on. Recursive consecutive queries initiated by PHP/C# or whatever code used.
I want to do this instead in one recursive (or other solution) MySQL query
The answer should focus only on a query solution (if possible) and not in organizing the database in another way. I am aware of other possible database designs which are more suitable for child parent relationships (such as closure tables, nested sets etc).
mysql select query recursive
mysql select query recursive
edited Jul 6 '18 at 13:03
Kristi Jorgji
asked Jul 6 '18 at 12:54
Kristi JorgjiKristi Jorgji
333
333
bumped to the homepage by Community♦ 24 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
bumped to the homepage by Community♦ 24 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
What version of MySQL are you using? I believe with 8.0 you can do what you want more easily: dev.mysql.com/doc/refman/8.0/en/with.html
– Willem Renzema
Jul 6 '18 at 13:19
Unfortunately it is version 5.7
– Kristi Jorgji
Jul 6 '18 at 13:21
Also, MariaDB 10.2 implemented such.
– Rick James
Jul 6 '18 at 13:31
add a comment |
What version of MySQL are you using? I believe with 8.0 you can do what you want more easily: dev.mysql.com/doc/refman/8.0/en/with.html
– Willem Renzema
Jul 6 '18 at 13:19
Unfortunately it is version 5.7
– Kristi Jorgji
Jul 6 '18 at 13:21
Also, MariaDB 10.2 implemented such.
– Rick James
Jul 6 '18 at 13:31
What version of MySQL are you using? I believe with 8.0 you can do what you want more easily: dev.mysql.com/doc/refman/8.0/en/with.html
– Willem Renzema
Jul 6 '18 at 13:19
What version of MySQL are you using? I believe with 8.0 you can do what you want more easily: dev.mysql.com/doc/refman/8.0/en/with.html
– Willem Renzema
Jul 6 '18 at 13:19
Unfortunately it is version 5.7
– Kristi Jorgji
Jul 6 '18 at 13:21
Unfortunately it is version 5.7
– Kristi Jorgji
Jul 6 '18 at 13:21
Also, MariaDB 10.2 implemented such.
– Rick James
Jul 6 '18 at 13:31
Also, MariaDB 10.2 implemented such.
– Rick James
Jul 6 '18 at 13:31
add a comment |
1 Answer
1
active
oldest
votes
Without additional information such as transitive closure or nested sets, you need some kind of iteration (well, if you know that the length of the chain cant be longer than n you could do that number of left joins). Since 5.7 does not support recursive CTE:s you can express the recursion in a stored procedure instead:
DELIMITER $$
CREATE OR REPLACE PROCEDURE materialized_path
(IN x BIGINT, IN acc text, OUT path TEXT)
BEGIN
DECLARE parent_ID INT DEFAULT NULL;
DECLARE tmppath text default '';
select original_action_id
from recurring_actions
where recurring_action_id = x into parent_ID;
IF parent_ID IS NULL THEN
SET path = rtrim(acc);
ELSE
CALL materialized_path(parent_ID, rtrim(acc)||parent_ID||',', path);
END IF;
END$$
DELIMITER ;
call materialized_path(5,'',@path); select @path;
Query OK, 0 rows affected, 1 warning (0.23 sec)
+--------+
| @path |
+--------+
| 3,2,1, |
+--------+
1 row in set (0.00 sec)
Now you need another procedural part that splits @path into its components and there ordinal numbers.
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "182"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f211540%2fhow-to-select-recursively-in-a-child-parent-design-situation-in-mysql%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Without additional information such as transitive closure or nested sets, you need some kind of iteration (well, if you know that the length of the chain cant be longer than n you could do that number of left joins). Since 5.7 does not support recursive CTE:s you can express the recursion in a stored procedure instead:
DELIMITER $$
CREATE OR REPLACE PROCEDURE materialized_path
(IN x BIGINT, IN acc text, OUT path TEXT)
BEGIN
DECLARE parent_ID INT DEFAULT NULL;
DECLARE tmppath text default '';
select original_action_id
from recurring_actions
where recurring_action_id = x into parent_ID;
IF parent_ID IS NULL THEN
SET path = rtrim(acc);
ELSE
CALL materialized_path(parent_ID, rtrim(acc)||parent_ID||',', path);
END IF;
END$$
DELIMITER ;
call materialized_path(5,'',@path); select @path;
Query OK, 0 rows affected, 1 warning (0.23 sec)
+--------+
| @path |
+--------+
| 3,2,1, |
+--------+
1 row in set (0.00 sec)
Now you need another procedural part that splits @path into its components and there ordinal numbers.
add a comment |
Without additional information such as transitive closure or nested sets, you need some kind of iteration (well, if you know that the length of the chain cant be longer than n you could do that number of left joins). Since 5.7 does not support recursive CTE:s you can express the recursion in a stored procedure instead:
DELIMITER $$
CREATE OR REPLACE PROCEDURE materialized_path
(IN x BIGINT, IN acc text, OUT path TEXT)
BEGIN
DECLARE parent_ID INT DEFAULT NULL;
DECLARE tmppath text default '';
select original_action_id
from recurring_actions
where recurring_action_id = x into parent_ID;
IF parent_ID IS NULL THEN
SET path = rtrim(acc);
ELSE
CALL materialized_path(parent_ID, rtrim(acc)||parent_ID||',', path);
END IF;
END$$
DELIMITER ;
call materialized_path(5,'',@path); select @path;
Query OK, 0 rows affected, 1 warning (0.23 sec)
+--------+
| @path |
+--------+
| 3,2,1, |
+--------+
1 row in set (0.00 sec)
Now you need another procedural part that splits @path into its components and there ordinal numbers.
add a comment |
Without additional information such as transitive closure or nested sets, you need some kind of iteration (well, if you know that the length of the chain cant be longer than n you could do that number of left joins). Since 5.7 does not support recursive CTE:s you can express the recursion in a stored procedure instead:
DELIMITER $$
CREATE OR REPLACE PROCEDURE materialized_path
(IN x BIGINT, IN acc text, OUT path TEXT)
BEGIN
DECLARE parent_ID INT DEFAULT NULL;
DECLARE tmppath text default '';
select original_action_id
from recurring_actions
where recurring_action_id = x into parent_ID;
IF parent_ID IS NULL THEN
SET path = rtrim(acc);
ELSE
CALL materialized_path(parent_ID, rtrim(acc)||parent_ID||',', path);
END IF;
END$$
DELIMITER ;
call materialized_path(5,'',@path); select @path;
Query OK, 0 rows affected, 1 warning (0.23 sec)
+--------+
| @path |
+--------+
| 3,2,1, |
+--------+
1 row in set (0.00 sec)
Now you need another procedural part that splits @path into its components and there ordinal numbers.
Without additional information such as transitive closure or nested sets, you need some kind of iteration (well, if you know that the length of the chain cant be longer than n you could do that number of left joins). Since 5.7 does not support recursive CTE:s you can express the recursion in a stored procedure instead:
DELIMITER $$
CREATE OR REPLACE PROCEDURE materialized_path
(IN x BIGINT, IN acc text, OUT path TEXT)
BEGIN
DECLARE parent_ID INT DEFAULT NULL;
DECLARE tmppath text default '';
select original_action_id
from recurring_actions
where recurring_action_id = x into parent_ID;
IF parent_ID IS NULL THEN
SET path = rtrim(acc);
ELSE
CALL materialized_path(parent_ID, rtrim(acc)||parent_ID||',', path);
END IF;
END$$
DELIMITER ;
call materialized_path(5,'',@path); select @path;
Query OK, 0 rows affected, 1 warning (0.23 sec)
+--------+
| @path |
+--------+
| 3,2,1, |
+--------+
1 row in set (0.00 sec)
Now you need another procedural part that splits @path into its components and there ordinal numbers.
answered Jul 6 '18 at 19:15
LennartLennart
12.5k21142
12.5k21142
add a comment |
add a comment |
Thanks for contributing an answer to Database Administrators Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f211540%2fhow-to-select-recursively-in-a-child-parent-design-situation-in-mysql%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What version of MySQL are you using? I believe with 8.0 you can do what you want more easily: dev.mysql.com/doc/refman/8.0/en/with.html
– Willem Renzema
Jul 6 '18 at 13:19
Unfortunately it is version 5.7
– Kristi Jorgji
Jul 6 '18 at 13:21
Also, MariaDB 10.2 implemented such.
– Rick James
Jul 6 '18 at 13:31