我正在尝试获取并显示基于product_id的所有parent_id名称。我正在做的是创建一个管理页面,我可以在其中添加特定产品的类别,但首先我需要在与parent_id相关联的categories表中获取每个名称,然后才能添加/编辑它们。
所以当我查询product_id 99时,我应该回来:滑板 - > action_sports - >运动
Categories Table
----------------------------------
| id | name | parent_id |
----------------------------------
| 1 | sports | null |
----------------------------------
| 2 | action_sports | 1 |
----------------------------------
| 3 | skateboarding | 2 |
----------------------------------
Product Category Joiner Table
----------------------------
| product_id | category_id |
----------------------------
| 99 | 3 |
----------------------------
我唯一能想到的是加入表格。我希望能够在不同的id上两次加入同一个表,但这显然不起作用。
SELECT categories.name, categories.parent_id FROM products
INNER JOIN product_category ON products.id = product_category.product_id
INNER JOIN categories ON categories.id = product_category.category_id
WHERE products.id = 99
returns:
-----------------------------
| name | parent_id |
-----------------------------
| skateboarding | 2 | <-- need to get name of each parent_id above
-----------------------------
有什么想法吗?希望我已经解释得足以让它有点意义
答案 0 :(得分:1)
您可以使用递归CTE,但首先是类别,但仅限于需要的类别:
with recursive cte as (
select c.id, c.name, c.parent_id
from products p join
categories c
on c.id = p.category_id
where p.product_id = 99
union all
select c.id, c.name, p.parent_id
from cte join
products p
on cte.parent = c.id
)
select *
from cte;
答案 1 :(得分:0)
如果您不知道有多少级别可以访问parent_id null
,您可以使用递归cte来解决此问题。
with recursive cte as
(select p.id as product_id,
c.name,
c.parent_id
from products p
join product_category pc on p.id = pc.product_id
join categories c on c.id = pc.category_id
union all
select p.id,
c.name,
c.parent_id
from cte r
join products p on p.id = r.product_id
join categories c on c.id = r.parent_id
)
select *
from cte
where product_id=99 --change this to the desired product_id