I have two tables with many to many relationship in Postresql database. The first Topic…
- User
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?
- Assistant
You can join the recursive query to the task table by using a subquery. Here's an example query that produces the desired result:
WITH RECURSIVE topic_hierarchy AS ( SELECT id, name, parent FROM topics WHERE id = 3
UNION
SELECT topics.id, topics.name, topics.parent FROM topics INNER JOIN topic_hierarchy ON topic_hierarchy.parent = topics.id ) SELECT task.id AS task_id, task.task, array_to_string(array_agg(topic_hierarchy.name ORDER BY topic_hierarchy.parent DESC), ' > ') AS topics_name, topic_hierarchy.parent AS topics_id FROM task INNER JOIN tasks_topics ON task.id = tasks_topics.task_id INNER JOIN topic_hierarchy ON tasks_topics.topic_id = topic_hierarchy.id GROUP BY task.id, task.task, topic_hierarchy.parent;
This query first defines a recursive query
topic_hierarchythat generates the hierarchy of topic parents for a given topic ID (in this case, 3). Then it joins thetasktable to thetasks_topicstable to get the topic IDs associated with each task, and joins that to thetopic_hierarchytable to get the name and parent ID of each topic. Finally, it groups the results by task and uses the function to aggregate all the topic names into an array, which is then converted to a string using .