SQL recursive query with multiple references to same tableAdd a column with a default value to an existing table in SQL ServerHow to concatenate text from multiple rows into a single text string in SQL server?SQL update from one Table to another based on a ID matchInserting multiple rows in a single SQL query?SQL multiple column orderingFinding duplicate values in a SQL tableWhat are the options for storing hierarchical data in a relational database?Find all tables containing column with specified name - MS SQL ServerHow to drop a table if it exists in SQL Server?SQL query return data from multiple tables
Three Dots in Center Page
Applications of pure mathematics in operations research
What would the United Kingdom's "optimal" Brexit deal look like?
What are the cons of stateless password generators?
Can I attune a Circlet of Human Perfection to my animated skeletons to allow them to blend in and speak?
Why would anyone ever invest in a cash-only etf?
Can a US President, after impeachment and removal, be re-elected or re-appointed?
What force enables us to walk? Friction or normal reaction?
Antonym of "Megalomania"
Are all French verb conjugation tenses and moods practical and efficient?
Unknown indication below upper stave
Is it okay for me to decline a project on ethical grounds?
Word for giving preference to the oldest child
What are the closest international airports in different countries?
Just how much information should you share with a former client?
Why would an invisible personal shield be necessary?
Correct word for a little toy that always stands up?
How to innovate in OR
Word for soundtrack music which is part of the action of the movie
How can flights operated by the same company have such different prices when marketed by another?
How to choose using Collection<Id> rather than Collection<String>, or the opposite?
How to prevent a single-element caster from being useless against immune foes?
Why does calling cout.operator<<(const char*) print the address instead of the character string?
Can you continue the movement of a Bonus Action Dash granted by Expeditious Retreat if your Concentration is broken mid-move?
SQL recursive query with multiple references to same table
Add a column with a default value to an existing table in SQL ServerHow to concatenate text from multiple rows into a single text string in SQL server?SQL update from one Table to another based on a ID matchInserting multiple rows in a single SQL query?SQL multiple column orderingFinding duplicate values in a SQL tableWhat are the options for storing hierarchical data in a relational database?Find all tables containing column with specified name - MS SQL ServerHow to drop a table if it exists in SQL Server?SQL query return data from multiple tables
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
Is there way to solve this problem with some sort of recursive SQL query (MySQL) rather than programmatically doing it.
I have two tables, one contains packages id and name, the other one contains id of package and parent_id which is also reference to id of some other package. What I need to achieve is to get list of all id of packages which contain some specific package.
Below is an example of tables and desired output if I'm looking for package with id 8. Package 8 is part of package 5 and 6, but package 6 is part of package 1 and 4. So, I need all of that ids as array(1,4,5,6).
packages table:
+----+-----------+
| id | name |
+----+-----------+
| 1 | package 1 |
| 2 | package 2 |
| 3 | package 3 |
| 4 | package 4 |
| 5 | package 5 |
| 6 | package 6 |
| 7 | package 7 |
| 8 | package 8 |
+----+-----------+
part_of table:
+----+-----------+
| id | parent_id |
+----+-----------+
| 6 | 1 |
| 6 | 4 |
| 8 | 5 |
| 8 | 6 |
+----+-----------+
output:
+----+
| id |
+----+
| 1 |
| 4 |
| 5 |
| 6 |
+----+
EDIT: To explain a bit better what this all was about. This packages table is actually car parts table, which also includes price and many more fields. If we look for "timing belt" part, it can be standalone, can be part of some bundle, we call it "timing belt set" or can be part of "full service" at workshop. All of them, "timing belt", "timing belt set", "full service" are stored in same table. Now, when customer comes asking for "timing belt", I can offer him standalone for 50$ or in set for 150$ or I can offer full service for 250$. All of them includes "timing belt" he asked for.
mysql sql recursive-query
add a comment |
Is there way to solve this problem with some sort of recursive SQL query (MySQL) rather than programmatically doing it.
I have two tables, one contains packages id and name, the other one contains id of package and parent_id which is also reference to id of some other package. What I need to achieve is to get list of all id of packages which contain some specific package.
Below is an example of tables and desired output if I'm looking for package with id 8. Package 8 is part of package 5 and 6, but package 6 is part of package 1 and 4. So, I need all of that ids as array(1,4,5,6).
packages table:
+----+-----------+
| id | name |
+----+-----------+
| 1 | package 1 |
| 2 | package 2 |
| 3 | package 3 |
| 4 | package 4 |
| 5 | package 5 |
| 6 | package 6 |
| 7 | package 7 |
| 8 | package 8 |
+----+-----------+
part_of table:
+----+-----------+
| id | parent_id |
+----+-----------+
| 6 | 1 |
| 6 | 4 |
| 8 | 5 |
| 8 | 6 |
+----+-----------+
output:
+----+
| id |
+----+
| 1 |
| 4 |
| 5 |
| 6 |
+----+
EDIT: To explain a bit better what this all was about. This packages table is actually car parts table, which also includes price and many more fields. If we look for "timing belt" part, it can be standalone, can be part of some bundle, we call it "timing belt set" or can be part of "full service" at workshop. All of them, "timing belt", "timing belt set", "full service" are stored in same table. Now, when customer comes asking for "timing belt", I can offer him standalone for 50$ or in set for 150$ or I can offer full service for 250$. All of them includes "timing belt" he asked for.
mysql sql recursive-query
Have you tried to write a query? Post what you have tried and what you have difficulties with and we can try to help.
– clinomaniac
Mar 26 at 21:40
No, I didn't because I'm not quite familiar with sql querying. So I wrote in php recursive function which uses more simple query. Get all parent_id for id 8, then foreach parent_id call function again. Results of all function calls are merged into one master array.
– Igor Pejašinović
Mar 26 at 21:48
MySQL only supports recursive CTEs in v8+. What version are you using?
– Gordon Linoff
Mar 26 at 21:50
1
MySQL 8.0 and MariaDB 10.2+ have recursive CTEs which will make this answer quite easy.
– danblack
Mar 26 at 21:52
mysql Ver 8.0.15 for Linux on x86_64 (MySQL Community Server - GPL)
– Igor Pejašinović
Mar 26 at 22:00
add a comment |
Is there way to solve this problem with some sort of recursive SQL query (MySQL) rather than programmatically doing it.
I have two tables, one contains packages id and name, the other one contains id of package and parent_id which is also reference to id of some other package. What I need to achieve is to get list of all id of packages which contain some specific package.
Below is an example of tables and desired output if I'm looking for package with id 8. Package 8 is part of package 5 and 6, but package 6 is part of package 1 and 4. So, I need all of that ids as array(1,4,5,6).
packages table:
+----+-----------+
| id | name |
+----+-----------+
| 1 | package 1 |
| 2 | package 2 |
| 3 | package 3 |
| 4 | package 4 |
| 5 | package 5 |
| 6 | package 6 |
| 7 | package 7 |
| 8 | package 8 |
+----+-----------+
part_of table:
+----+-----------+
| id | parent_id |
+----+-----------+
| 6 | 1 |
| 6 | 4 |
| 8 | 5 |
| 8 | 6 |
+----+-----------+
output:
+----+
| id |
+----+
| 1 |
| 4 |
| 5 |
| 6 |
+----+
EDIT: To explain a bit better what this all was about. This packages table is actually car parts table, which also includes price and many more fields. If we look for "timing belt" part, it can be standalone, can be part of some bundle, we call it "timing belt set" or can be part of "full service" at workshop. All of them, "timing belt", "timing belt set", "full service" are stored in same table. Now, when customer comes asking for "timing belt", I can offer him standalone for 50$ or in set for 150$ or I can offer full service for 250$. All of them includes "timing belt" he asked for.
mysql sql recursive-query
Is there way to solve this problem with some sort of recursive SQL query (MySQL) rather than programmatically doing it.
I have two tables, one contains packages id and name, the other one contains id of package and parent_id which is also reference to id of some other package. What I need to achieve is to get list of all id of packages which contain some specific package.
Below is an example of tables and desired output if I'm looking for package with id 8. Package 8 is part of package 5 and 6, but package 6 is part of package 1 and 4. So, I need all of that ids as array(1,4,5,6).
packages table:
+----+-----------+
| id | name |
+----+-----------+
| 1 | package 1 |
| 2 | package 2 |
| 3 | package 3 |
| 4 | package 4 |
| 5 | package 5 |
| 6 | package 6 |
| 7 | package 7 |
| 8 | package 8 |
+----+-----------+
part_of table:
+----+-----------+
| id | parent_id |
+----+-----------+
| 6 | 1 |
| 6 | 4 |
| 8 | 5 |
| 8 | 6 |
+----+-----------+
output:
+----+
| id |
+----+
| 1 |
| 4 |
| 5 |
| 6 |
+----+
EDIT: To explain a bit better what this all was about. This packages table is actually car parts table, which also includes price and many more fields. If we look for "timing belt" part, it can be standalone, can be part of some bundle, we call it "timing belt set" or can be part of "full service" at workshop. All of them, "timing belt", "timing belt set", "full service" are stored in same table. Now, when customer comes asking for "timing belt", I can offer him standalone for 50$ or in set for 150$ or I can offer full service for 250$. All of them includes "timing belt" he asked for.
mysql sql recursive-query
mysql sql recursive-query
edited Mar 27 at 0:28
Igor Pejašinović
asked Mar 26 at 21:36
Igor PejašinovićIgor Pejašinović
187 bronze badges
187 bronze badges
Have you tried to write a query? Post what you have tried and what you have difficulties with and we can try to help.
– clinomaniac
Mar 26 at 21:40
No, I didn't because I'm not quite familiar with sql querying. So I wrote in php recursive function which uses more simple query. Get all parent_id for id 8, then foreach parent_id call function again. Results of all function calls are merged into one master array.
– Igor Pejašinović
Mar 26 at 21:48
MySQL only supports recursive CTEs in v8+. What version are you using?
– Gordon Linoff
Mar 26 at 21:50
1
MySQL 8.0 and MariaDB 10.2+ have recursive CTEs which will make this answer quite easy.
– danblack
Mar 26 at 21:52
mysql Ver 8.0.15 for Linux on x86_64 (MySQL Community Server - GPL)
– Igor Pejašinović
Mar 26 at 22:00
add a comment |
Have you tried to write a query? Post what you have tried and what you have difficulties with and we can try to help.
– clinomaniac
Mar 26 at 21:40
No, I didn't because I'm not quite familiar with sql querying. So I wrote in php recursive function which uses more simple query. Get all parent_id for id 8, then foreach parent_id call function again. Results of all function calls are merged into one master array.
– Igor Pejašinović
Mar 26 at 21:48
MySQL only supports recursive CTEs in v8+. What version are you using?
– Gordon Linoff
Mar 26 at 21:50
1
MySQL 8.0 and MariaDB 10.2+ have recursive CTEs which will make this answer quite easy.
– danblack
Mar 26 at 21:52
mysql Ver 8.0.15 for Linux on x86_64 (MySQL Community Server - GPL)
– Igor Pejašinović
Mar 26 at 22:00
Have you tried to write a query? Post what you have tried and what you have difficulties with and we can try to help.
– clinomaniac
Mar 26 at 21:40
Have you tried to write a query? Post what you have tried and what you have difficulties with and we can try to help.
– clinomaniac
Mar 26 at 21:40
No, I didn't because I'm not quite familiar with sql querying. So I wrote in php recursive function which uses more simple query. Get all parent_id for id 8, then foreach parent_id call function again. Results of all function calls are merged into one master array.
– Igor Pejašinović
Mar 26 at 21:48
No, I didn't because I'm not quite familiar with sql querying. So I wrote in php recursive function which uses more simple query. Get all parent_id for id 8, then foreach parent_id call function again. Results of all function calls are merged into one master array.
– Igor Pejašinović
Mar 26 at 21:48
MySQL only supports recursive CTEs in v8+. What version are you using?
– Gordon Linoff
Mar 26 at 21:50
MySQL only supports recursive CTEs in v8+. What version are you using?
– Gordon Linoff
Mar 26 at 21:50
1
1
MySQL 8.0 and MariaDB 10.2+ have recursive CTEs which will make this answer quite easy.
– danblack
Mar 26 at 21:52
MySQL 8.0 and MariaDB 10.2+ have recursive CTEs which will make this answer quite easy.
– danblack
Mar 26 at 21:52
mysql Ver 8.0.15 for Linux on x86_64 (MySQL Community Server - GPL)
– Igor Pejašinović
Mar 26 at 22:00
mysql Ver 8.0.15 for Linux on x86_64 (MySQL Community Server - GPL)
– Igor Pejašinović
Mar 26 at 22:00
add a comment |
3 Answers
3
active
oldest
votes
You should be able to achieve this using a MySQL recursive common table expression:
WITH RECURSIVE cte AS (
SELECT id, parent_id FROM part_of WHERE id = 8
UNION ALL
SELECT po.id, po.parent_id FROM part_of po INNER JOIN cte ON cte.parent_id = po.id
)
SELECT parent_id FROM cte
Demo on DB fiddle:
| parent_id |
| --------- |
| 5 |
| 6 |
| 1 |
| 4 |
You can JOIN
the results with the products
table to show the name of each parent product:
WITH RECURSIVE cte AS (
SELECT id, parent_id FROM part_of WHERE id = 8
UNION ALL
SELECT po.id, po.parent_id FROM part_of po INNER JOIN cte ON cte.parent_id = po.id
)
SELECT cte.parent_id, p.name
FROM cte
INNER JOIN packages p on cte.parent_id = p.id
Demo on DB Fiddle:
| parent_id | name |
| --------- | --------- |
| 1 | package 1 |
| 4 | package 4 |
| 5 | package 5 |
| 6 | package 6 |
I am pretty sure he will still need to the packages table. I his example, he uses package 8. I assume he wants to get the ID for package 8 and then join onto the part_of table. I could be wrong, hopefully @IgorPejašinović will provide some insight.
– MhQ-6
Mar 26 at 22:58
1
@GMB first solution is right answer. packages table is just about feeling what this is all about. I'm using it just to find starting id.
– Igor Pejašinović
Mar 27 at 0:09
add a comment |
Why not use part_of table twice ? join the part-of table itself self join
and then query for the id ? it really depends on what level of recursion you are looking for i guess.
add a comment |
I writing this answer assuming that you will need the packages tables to get the ID, which will then be used to get the parent_id from the part_of table. This part was a bit unclear in your question. If I am wrong in assuming this, then @GBM answer will work as well, as well as mine.
WITH PACKAGES_CTE AS (
SELECT PACKAGES.ID, PACKAGES.NAME
FROM PACKAGES
), PACKAGES2_CTE AS
(
SELECT *
FROM PACKAGES2
)
SELECT P2.PARENT_ID
FROM PACKAGES2_CTE P2
LEFT JOIN PACKAGES2_CTE P3 ON P3.PARENT_ID = P2.ID
WHERE P3.ID = 8
UNION ALL
SELECT P2.PARENT_ID
FROM PACKAGES_CTE P
LEFT JOIN PACKAGES2_CTE P2 ON P.ID = P2.ID
WHERE P2.ID = P2.PARENT_ID OR P.ID = 8
If you have any questions feel free to ask. I did test this using the sample data you provided. Since I already knew the ID, I did not need to use the Packages.Name. I assume you will want to use Packages.Name = 'Package 8' instead of P.ID = 8.
This was an interesting problem!
packages table is just there to get some feeling about what this is. Im using it just to find starting id. With your solution, I get result I want for this example in first post, but if I add new row in part_of, lets say package 4 has parent 2, it stops working. that's why i think, it must be some recursive query.
– Igor Pejašinović
Mar 27 at 0:11
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
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: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
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%2fstackoverflow.com%2fquestions%2f55366572%2fsql-recursive-query-with-multiple-references-to-same-table%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
You should be able to achieve this using a MySQL recursive common table expression:
WITH RECURSIVE cte AS (
SELECT id, parent_id FROM part_of WHERE id = 8
UNION ALL
SELECT po.id, po.parent_id FROM part_of po INNER JOIN cte ON cte.parent_id = po.id
)
SELECT parent_id FROM cte
Demo on DB fiddle:
| parent_id |
| --------- |
| 5 |
| 6 |
| 1 |
| 4 |
You can JOIN
the results with the products
table to show the name of each parent product:
WITH RECURSIVE cte AS (
SELECT id, parent_id FROM part_of WHERE id = 8
UNION ALL
SELECT po.id, po.parent_id FROM part_of po INNER JOIN cte ON cte.parent_id = po.id
)
SELECT cte.parent_id, p.name
FROM cte
INNER JOIN packages p on cte.parent_id = p.id
Demo on DB Fiddle:
| parent_id | name |
| --------- | --------- |
| 1 | package 1 |
| 4 | package 4 |
| 5 | package 5 |
| 6 | package 6 |
I am pretty sure he will still need to the packages table. I his example, he uses package 8. I assume he wants to get the ID for package 8 and then join onto the part_of table. I could be wrong, hopefully @IgorPejašinović will provide some insight.
– MhQ-6
Mar 26 at 22:58
1
@GMB first solution is right answer. packages table is just about feeling what this is all about. I'm using it just to find starting id.
– Igor Pejašinović
Mar 27 at 0:09
add a comment |
You should be able to achieve this using a MySQL recursive common table expression:
WITH RECURSIVE cte AS (
SELECT id, parent_id FROM part_of WHERE id = 8
UNION ALL
SELECT po.id, po.parent_id FROM part_of po INNER JOIN cte ON cte.parent_id = po.id
)
SELECT parent_id FROM cte
Demo on DB fiddle:
| parent_id |
| --------- |
| 5 |
| 6 |
| 1 |
| 4 |
You can JOIN
the results with the products
table to show the name of each parent product:
WITH RECURSIVE cte AS (
SELECT id, parent_id FROM part_of WHERE id = 8
UNION ALL
SELECT po.id, po.parent_id FROM part_of po INNER JOIN cte ON cte.parent_id = po.id
)
SELECT cte.parent_id, p.name
FROM cte
INNER JOIN packages p on cte.parent_id = p.id
Demo on DB Fiddle:
| parent_id | name |
| --------- | --------- |
| 1 | package 1 |
| 4 | package 4 |
| 5 | package 5 |
| 6 | package 6 |
I am pretty sure he will still need to the packages table. I his example, he uses package 8. I assume he wants to get the ID for package 8 and then join onto the part_of table. I could be wrong, hopefully @IgorPejašinović will provide some insight.
– MhQ-6
Mar 26 at 22:58
1
@GMB first solution is right answer. packages table is just about feeling what this is all about. I'm using it just to find starting id.
– Igor Pejašinović
Mar 27 at 0:09
add a comment |
You should be able to achieve this using a MySQL recursive common table expression:
WITH RECURSIVE cte AS (
SELECT id, parent_id FROM part_of WHERE id = 8
UNION ALL
SELECT po.id, po.parent_id FROM part_of po INNER JOIN cte ON cte.parent_id = po.id
)
SELECT parent_id FROM cte
Demo on DB fiddle:
| parent_id |
| --------- |
| 5 |
| 6 |
| 1 |
| 4 |
You can JOIN
the results with the products
table to show the name of each parent product:
WITH RECURSIVE cte AS (
SELECT id, parent_id FROM part_of WHERE id = 8
UNION ALL
SELECT po.id, po.parent_id FROM part_of po INNER JOIN cte ON cte.parent_id = po.id
)
SELECT cte.parent_id, p.name
FROM cte
INNER JOIN packages p on cte.parent_id = p.id
Demo on DB Fiddle:
| parent_id | name |
| --------- | --------- |
| 1 | package 1 |
| 4 | package 4 |
| 5 | package 5 |
| 6 | package 6 |
You should be able to achieve this using a MySQL recursive common table expression:
WITH RECURSIVE cte AS (
SELECT id, parent_id FROM part_of WHERE id = 8
UNION ALL
SELECT po.id, po.parent_id FROM part_of po INNER JOIN cte ON cte.parent_id = po.id
)
SELECT parent_id FROM cte
Demo on DB fiddle:
| parent_id |
| --------- |
| 5 |
| 6 |
| 1 |
| 4 |
You can JOIN
the results with the products
table to show the name of each parent product:
WITH RECURSIVE cte AS (
SELECT id, parent_id FROM part_of WHERE id = 8
UNION ALL
SELECT po.id, po.parent_id FROM part_of po INNER JOIN cte ON cte.parent_id = po.id
)
SELECT cte.parent_id, p.name
FROM cte
INNER JOIN packages p on cte.parent_id = p.id
Demo on DB Fiddle:
| parent_id | name |
| --------- | --------- |
| 1 | package 1 |
| 4 | package 4 |
| 5 | package 5 |
| 6 | package 6 |
edited Mar 26 at 23:21
answered Mar 26 at 22:56
GMBGMB
22.3k6 gold badges11 silver badges28 bronze badges
22.3k6 gold badges11 silver badges28 bronze badges
I am pretty sure he will still need to the packages table. I his example, he uses package 8. I assume he wants to get the ID for package 8 and then join onto the part_of table. I could be wrong, hopefully @IgorPejašinović will provide some insight.
– MhQ-6
Mar 26 at 22:58
1
@GMB first solution is right answer. packages table is just about feeling what this is all about. I'm using it just to find starting id.
– Igor Pejašinović
Mar 27 at 0:09
add a comment |
I am pretty sure he will still need to the packages table. I his example, he uses package 8. I assume he wants to get the ID for package 8 and then join onto the part_of table. I could be wrong, hopefully @IgorPejašinović will provide some insight.
– MhQ-6
Mar 26 at 22:58
1
@GMB first solution is right answer. packages table is just about feeling what this is all about. I'm using it just to find starting id.
– Igor Pejašinović
Mar 27 at 0:09
I am pretty sure he will still need to the packages table. I his example, he uses package 8. I assume he wants to get the ID for package 8 and then join onto the part_of table. I could be wrong, hopefully @IgorPejašinović will provide some insight.
– MhQ-6
Mar 26 at 22:58
I am pretty sure he will still need to the packages table. I his example, he uses package 8. I assume he wants to get the ID for package 8 and then join onto the part_of table. I could be wrong, hopefully @IgorPejašinović will provide some insight.
– MhQ-6
Mar 26 at 22:58
1
1
@GMB first solution is right answer. packages table is just about feeling what this is all about. I'm using it just to find starting id.
– Igor Pejašinović
Mar 27 at 0:09
@GMB first solution is right answer. packages table is just about feeling what this is all about. I'm using it just to find starting id.
– Igor Pejašinović
Mar 27 at 0:09
add a comment |
Why not use part_of table twice ? join the part-of table itself self join
and then query for the id ? it really depends on what level of recursion you are looking for i guess.
add a comment |
Why not use part_of table twice ? join the part-of table itself self join
and then query for the id ? it really depends on what level of recursion you are looking for i guess.
add a comment |
Why not use part_of table twice ? join the part-of table itself self join
and then query for the id ? it really depends on what level of recursion you are looking for i guess.
Why not use part_of table twice ? join the part-of table itself self join
and then query for the id ? it really depends on what level of recursion you are looking for i guess.
answered Mar 26 at 22:07
user3342678user3342678
113 bronze badges
113 bronze badges
add a comment |
add a comment |
I writing this answer assuming that you will need the packages tables to get the ID, which will then be used to get the parent_id from the part_of table. This part was a bit unclear in your question. If I am wrong in assuming this, then @GBM answer will work as well, as well as mine.
WITH PACKAGES_CTE AS (
SELECT PACKAGES.ID, PACKAGES.NAME
FROM PACKAGES
), PACKAGES2_CTE AS
(
SELECT *
FROM PACKAGES2
)
SELECT P2.PARENT_ID
FROM PACKAGES2_CTE P2
LEFT JOIN PACKAGES2_CTE P3 ON P3.PARENT_ID = P2.ID
WHERE P3.ID = 8
UNION ALL
SELECT P2.PARENT_ID
FROM PACKAGES_CTE P
LEFT JOIN PACKAGES2_CTE P2 ON P.ID = P2.ID
WHERE P2.ID = P2.PARENT_ID OR P.ID = 8
If you have any questions feel free to ask. I did test this using the sample data you provided. Since I already knew the ID, I did not need to use the Packages.Name. I assume you will want to use Packages.Name = 'Package 8' instead of P.ID = 8.
This was an interesting problem!
packages table is just there to get some feeling about what this is. Im using it just to find starting id. With your solution, I get result I want for this example in first post, but if I add new row in part_of, lets say package 4 has parent 2, it stops working. that's why i think, it must be some recursive query.
– Igor Pejašinović
Mar 27 at 0:11
add a comment |
I writing this answer assuming that you will need the packages tables to get the ID, which will then be used to get the parent_id from the part_of table. This part was a bit unclear in your question. If I am wrong in assuming this, then @GBM answer will work as well, as well as mine.
WITH PACKAGES_CTE AS (
SELECT PACKAGES.ID, PACKAGES.NAME
FROM PACKAGES
), PACKAGES2_CTE AS
(
SELECT *
FROM PACKAGES2
)
SELECT P2.PARENT_ID
FROM PACKAGES2_CTE P2
LEFT JOIN PACKAGES2_CTE P3 ON P3.PARENT_ID = P2.ID
WHERE P3.ID = 8
UNION ALL
SELECT P2.PARENT_ID
FROM PACKAGES_CTE P
LEFT JOIN PACKAGES2_CTE P2 ON P.ID = P2.ID
WHERE P2.ID = P2.PARENT_ID OR P.ID = 8
If you have any questions feel free to ask. I did test this using the sample data you provided. Since I already knew the ID, I did not need to use the Packages.Name. I assume you will want to use Packages.Name = 'Package 8' instead of P.ID = 8.
This was an interesting problem!
packages table is just there to get some feeling about what this is. Im using it just to find starting id. With your solution, I get result I want for this example in first post, but if I add new row in part_of, lets say package 4 has parent 2, it stops working. that's why i think, it must be some recursive query.
– Igor Pejašinović
Mar 27 at 0:11
add a comment |
I writing this answer assuming that you will need the packages tables to get the ID, which will then be used to get the parent_id from the part_of table. This part was a bit unclear in your question. If I am wrong in assuming this, then @GBM answer will work as well, as well as mine.
WITH PACKAGES_CTE AS (
SELECT PACKAGES.ID, PACKAGES.NAME
FROM PACKAGES
), PACKAGES2_CTE AS
(
SELECT *
FROM PACKAGES2
)
SELECT P2.PARENT_ID
FROM PACKAGES2_CTE P2
LEFT JOIN PACKAGES2_CTE P3 ON P3.PARENT_ID = P2.ID
WHERE P3.ID = 8
UNION ALL
SELECT P2.PARENT_ID
FROM PACKAGES_CTE P
LEFT JOIN PACKAGES2_CTE P2 ON P.ID = P2.ID
WHERE P2.ID = P2.PARENT_ID OR P.ID = 8
If you have any questions feel free to ask. I did test this using the sample data you provided. Since I already knew the ID, I did not need to use the Packages.Name. I assume you will want to use Packages.Name = 'Package 8' instead of P.ID = 8.
This was an interesting problem!
I writing this answer assuming that you will need the packages tables to get the ID, which will then be used to get the parent_id from the part_of table. This part was a bit unclear in your question. If I am wrong in assuming this, then @GBM answer will work as well, as well as mine.
WITH PACKAGES_CTE AS (
SELECT PACKAGES.ID, PACKAGES.NAME
FROM PACKAGES
), PACKAGES2_CTE AS
(
SELECT *
FROM PACKAGES2
)
SELECT P2.PARENT_ID
FROM PACKAGES2_CTE P2
LEFT JOIN PACKAGES2_CTE P3 ON P3.PARENT_ID = P2.ID
WHERE P3.ID = 8
UNION ALL
SELECT P2.PARENT_ID
FROM PACKAGES_CTE P
LEFT JOIN PACKAGES2_CTE P2 ON P.ID = P2.ID
WHERE P2.ID = P2.PARENT_ID OR P.ID = 8
If you have any questions feel free to ask. I did test this using the sample data you provided. Since I already knew the ID, I did not need to use the Packages.Name. I assume you will want to use Packages.Name = 'Package 8' instead of P.ID = 8.
This was an interesting problem!
answered Mar 26 at 23:13
MhQ-6MhQ-6
1688 bronze badges
1688 bronze badges
packages table is just there to get some feeling about what this is. Im using it just to find starting id. With your solution, I get result I want for this example in first post, but if I add new row in part_of, lets say package 4 has parent 2, it stops working. that's why i think, it must be some recursive query.
– Igor Pejašinović
Mar 27 at 0:11
add a comment |
packages table is just there to get some feeling about what this is. Im using it just to find starting id. With your solution, I get result I want for this example in first post, but if I add new row in part_of, lets say package 4 has parent 2, it stops working. that's why i think, it must be some recursive query.
– Igor Pejašinović
Mar 27 at 0:11
packages table is just there to get some feeling about what this is. Im using it just to find starting id. With your solution, I get result I want for this example in first post, but if I add new row in part_of, lets say package 4 has parent 2, it stops working. that's why i think, it must be some recursive query.
– Igor Pejašinović
Mar 27 at 0:11
packages table is just there to get some feeling about what this is. Im using it just to find starting id. With your solution, I get result I want for this example in first post, but if I add new row in part_of, lets say package 4 has parent 2, it stops working. that's why i think, it must be some recursive query.
– Igor Pejašinović
Mar 27 at 0:11
add a comment |
Thanks for contributing an answer to Stack Overflow!
- 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%2fstackoverflow.com%2fquestions%2f55366572%2fsql-recursive-query-with-multiple-references-to-same-table%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
Have you tried to write a query? Post what you have tried and what you have difficulties with and we can try to help.
– clinomaniac
Mar 26 at 21:40
No, I didn't because I'm not quite familiar with sql querying. So I wrote in php recursive function which uses more simple query. Get all parent_id for id 8, then foreach parent_id call function again. Results of all function calls are merged into one master array.
– Igor Pejašinović
Mar 26 at 21:48
MySQL only supports recursive CTEs in v8+. What version are you using?
– Gordon Linoff
Mar 26 at 21:50
1
MySQL 8.0 and MariaDB 10.2+ have recursive CTEs which will make this answer quite easy.
– danblack
Mar 26 at 21:52
mysql Ver 8.0.15 for Linux on x86_64 (MySQL Community Server - GPL)
– Igor Pejašinović
Mar 26 at 22:00