I have two tables with many to many relationship in Postresql database.
The first Topic table consists of three columns. Their names are id, name and parent. Topic table has hierarchial structure:
id | name | parent |
---|---|---|
1 | Mathematics | 0 |
2 | Algebra | 1 |
3 | Progression | 2 |
4 | Number sequences | 3 |
5 | Arithmetics | 1 |
6 | sum values | 5 |
The second table has name task table. It has two columns – task id and task text:
id | task |
---|---|
100 | 1+2+3+4 |
101 | 1+2 |
tasks_topics table is
task_id | topics_id |
---|---|
100 | 3 |
100 | 6 |
101 | 1 |
I need to get the table jointed to recursive query of topic. It should consists of four columns. THe first column should be task_id, the second task text, the third should be al parent names of topic tasks. And the last one should be parent topic id.
The result should be:
task_id | name | topics_name | topics_id |
---|---|---|---|
100 | 1+2+3+4 | sum values | 6 |
100 | 1+2+3+4 | Arithmetics | 5 |
100 | 1+2+3+4 | Progression | 3 |
100 | 1+2+3+4 | Algebra | 2 |
100 | 1+2+3+4 | Mathematics | 1 |
101 | 1+2 | Mathematics | 1 |
I can make recursive query to topic table
WITH RECURSIVE topic_parent AS (
SELECT
id,
name,
parent
FROM
topics
WHERE
id = 3
UNION
SELECT
topics.id,
topics.name,
topics.parent
FROM
topics
INNER JOIN topic_parent ON topic_parent.parent = topics.id
)
SELECT
*
FROM
topic_parent
;
but I don’t know ho to join it to task by id.
How should I solve this problem?
2
Answers
First cte (
WITH RECURSIVE
) is to get topics parents,cte2
to convert the array of topics to rows,Then we join data together to get the expected result.
Demo here
should produce result as per below:
via SQL along these lines: