我已经改编自here。
SELECT T2.id, T2.name
FROM (
SELECT
@r AS _id,
(SELECT @r := category_id_parent FROM category WHERE id = _id) AS category_id_parent,
@l := @l + 1 AS lvl
FROM
(SELECT @r := (SELECT c.id FROM category c WHERE c.name="Category D"), @l := 0) vars,
category h
WHERE @r <> -1) T1
JOIN category T2
ON T1._id = T2.id
ORDER BY T1.lvl DESC
我将如何进一步调整以接受ID列表而不是一个ID?
所以不是SELECT c.id FROM category c WHERE c.name="Category D"
它将是SELECT bc.category_id FROM businesscategory bc WHERE bc.business_id=55
(返回一个ID列表,而不是一个ID列表)
当前查询示例:
我有一张桌子category
id | name | category_id_parent
-1 N/A -1
1 Category A -1
2 Category B -1
3 Category C 1
4 Category D 3
此查询将返回
id | name
1 Category A
3 Category C
4 Category D
由于类别D的父代为C,父代为A。