我有一个表,其中包含项,而表中的类别与ManyToMany关系中的关系。
项目
id | name
1 name1
2 name2
3 name3
ItemCategory
id | category_id | item_id
1 4 1
2 5 1
3 7 1
4 8 1
类别(其parent_id外键)
id | parent_id | name
1 Null A1
2 1 B1
3 1 B2
4 2 C1
5 3 C2
6 1 D1
7 6 DE
8 1 DT
我正在尝试获取某项的从子项到父项的项类别,所以我使用:
WITH RECURSIVE descendants(name, id, slug, parent_id, bread_order) AS (
SELECT name, id, slug, parent_id, 0
FROM categories
where id in (
SELECT c.id FROM items AS p
INNER JOIN items_categories AS pc ON p.id=pc.item_id
INNER JOIN categories AS c ON pc.category_id = c.id
WHERE p.id = 10
)
UNION ALL
SELECT c2.name, c2.id, c2.slug, c2.parent_id, bread_order+1
FROM categories AS c2
INNER JOIN descendants AS d ON c2.id=d.parent_id
) SELECT id, name, parent_id, bread_order FROM descendants
ORDER by bread_order DESC
问题在于两个子类别可以具有相同的父项,或者一个子类别的父项是另一个父项。
C1 -> B1 -> A1
C2 ->B1 -> A1
C3 ->B2 -> A1
DE -> D1 -> A1
DT -> A1
我试图对它们进行分组,但是由于有相同的父母,所以我不需要grand_parents,因此当我从数据库中检索信息以了解如何创建路径时,我就需要这样做(见上文)。
有什么办法,例如将CASE与从子查询返回的ID一起使用?
答案 0 :(得分:1)
您可以在查询期间汇总路径:
WITH RECURSIVE descendants(name, id, parent_id, bread_order, path) AS (
SELECT name, id, parent_id, 0, array[id] as path
FROM categories
where id in (SELECT c.id
FROM items AS p
JOIN items_categories AS pc ON p.id=pc.item_id
JOIN categories AS c ON pc.category_id = c.id
WHERE p.id = 1)
UNION ALL
SELECT c2.name, c2.id, c2.parent_id, bread_order+1, d.path||c2.id
FROM categories AS c2
JOIN descendants AS d ON c2.id=d.parent_id
)
SELECT id, name, parent_id, path, bread_order
FROM descendants
ORDER by path