2 回答

TA貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
所以當(dāng)我做對(duì)了你想要得到一棵樹的葉子。如果您沒有嚴(yán)格限制,recursive CTE您可以簡單地檢查給定類別是否有子級(jí)。如果不是 - 它是一個(gè)葉子(尊重相同的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
每個(gè)父母的情況,這將是行不通的。

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
嘗試使用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 關(guān)注
- 123 瀏覽
添加回答
舉報(bào)