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 關注
- 125 瀏覽
添加回答
舉報