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
;
- Assistant
However, to join it with the task table and the tasks_topics table, you can use the following query:
WITH RECURSIVE topic_parent AS ( SELECT id, name, parent FROM topics WHERE id IN (SELECT topics_id FROM tasks_topics) UNION SELECT topics.id, topics.name, topics.parent FROM topics INNER JOIN topic_parent ON topic_parent.parent = topics.id ) SELECT tasks.id AS task_id, tasks.task, string_agg(topic_parent.name, ' -> ') AS topics_name, topic_parent.id AS topics_id FROM tasks INNER JOIN tasks_topics ON tasks.id = tasks_topics.task_id INNER JOIN topic_parent ON tasks_topics.topics_id = topic_parent.id GROUP BY tasks.id, tasks.task, topic_parent.id;
This query first uses the tasks_topics table to filter the relevant topics using a subquery. Then, it uses a recursive CTE to get all the parent topics for each relevant topic. Finally, it joins the tasks table with tasks_topics and topic_parent to get the desired result, using string_agg to concatenate all the parent names of each topic into one column.
- User
Данный код не возвращает всю рекурсивную зависимость
- Assistant
Извините за предыдущий ответ, я ошибся. Действительно, запрос не возвращает всю рекурсивную зависимость.
Чтобы получить полную рекурсивную зависимость, нужно использовать больше уровней рекурсии в CTE. Например, в этом случае можно использовать максимальную глубину рекурсии, которая равна 100 в PostgreSQL.
Вот исправленный запрос:
WITH RECURSIVE topic_parent AS ( SELECT id, name, parent, id AS root_id, name AS root_name FROM topics WHERE id IN (SELECT topics_id FROM tasks_topics) UNION SELECT topics.id, topics.name, topics.parent, topic_parent.root_id, topic_parent.root_name || ' -> ' || topics.name FROM topics INNER JOIN topic_parent ON topic_parent.parent = topics.id WHERE topic_parent.depth < 100 ) SELECT tasks.id AS task_id, tasks.task, topic_parent.root_name AS name, topic_parent.root_id AS topics_id FROM tasks INNER JOIN tasks_topics ON tasks.id = tasks_topics.task_id INNER JOIN topic_parent ON tasks_topics.topics_id = topic_parent.id WHERE topic_parent.parent = 0;
Здесь мы добавляем два дополнительных поля в рекурсивный CTE: root_id и root_name. Root_id - это идентификатор корневой темы, а root_name - это имя всей цепочки родительских тем для данной темы. Мы также добавляем условие, что глубина рекурсии должна быть меньше 100, чтобы избежать бесконечной рекурсии.
- User
ERROR: column topic_parent.depth does not exist LINE 23: topic_parent.depth < 100 ^ SQL state: 42703 Character: 352
- Assistant
Извините за ошибку. Действительно, в предыдущем запросе не был указан столбец depth в рекурсивном CTE.
Вот исправленный запрос:
WITH RECURSIVE topic_parent AS ( SELECT id, name, parent, id AS root_id, name AS root_name, 1 AS depth FROM topics WHERE id IN (SELECT topics_id FROM tasks_topics) UNION SELECT topics.id, topics.name, topics.parent, topic_parent.root_id, topic_parent.root_name || ' -> ' || topics.name, topic_parent.depth + 1 FROM topics INNER JOIN topic_parent ON topic_parent.parent = topics.id WHERE topic_parent.depth < 100 ) SELECT tasks.id AS task_id, tasks.task, topic_parent.root_name AS name, topic_parent.root_id AS topics_id FROM tasks INNER JOIN tasks_topics ON tasks.id = tasks_topics.task_id INNER JOIN topic_parent ON tasks_topics.topics_id = topic_parent.id WHERE topic_parent.parent = 0;
Здесь мы добавляем столбец depth в первый SELECT в рекурсивной части запроса и устанавливаем его значение равным 1. Затем мы добавляем это же поле во второй SELECT и увеличиваем его значение на 1 при каждой рекурсивной итерации.
Затем мы изменяем условие в WHERE для ограничения глубины рекурсии на основе столбца depth.
Теперь запрос должен работать правильно. Извините за предыдущие неудачные попытки.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.