2 回答
TA贡献1893条经验 获得超10个赞
所以当我做对了你想要得到一棵树的叶子。如果您没有严格限制,recursive CTE您可以简单地检查给定类别是否有子级。如果不是 - 它是一个叶子(尊重相同的product_id)。
SELECT product_id, category_id
FROM categories c
WHERE
(
SELECT
count(*)
FROM
categories c2
WHERE
c2.parent_category = c.category_id
AND c2.product_id = c.product_id
) = 0
工作示例。
如果你想检查product_id
每个父母的情况,这将是行不通的。
TA贡献1880条经验 获得超4个赞
尝试使用recursive CTE:
with recursive cte as (
select
*, 0 as level, concat(product_id, '-', category_id) as ar
from
samp
where
parent_category ='0'
union all
select
t1.*, t2.level+1, ar
from samp t1
inner join
cte t2
on t1.parent_category =t2.category_id and t1.product_id=t2.product_id
),
cte1 as (
select
*, row_number() over (partition by ar order by level desc) as rank_
from
cte
)
select
product_id, category_id, parent_category
from
cte1
where
rank_=1
- 2 回答
- 0 关注
- 89 浏览
添加回答
举报