Currently I use the following CTE to grab a category and any category below it:
WITH RECURSIVE tree AS (
SELECT * FROM (
SELECT categoryId,
categoryName,
categoryParentId,
categoryDescr,
categoryType,
categoryDC,
categoryLedgerId,
1 as categoryDepth
FROM tbl_categories
WHERE categoryId = '.$categoryId.'
UNION
SELECT categoryId,
categoryName,
categoryParentId,
categoryDescr,
categoryType,
categoryDC,
categoryLedgerId,
1 as categoryDepth
FROM tbl_categories_custom
WHERE categoryId = '.$categoryId.'
) AS combined
UNION ALL
SELECT p.categoryId,
p.categoryName,
p.categoryParentId,
p.categoryDescr,
p.categoryType,
p.categoryDC,
p.categoryLedgerId,
t.categoryDepth + 1
FROM (
SELECT * FROM tbl_categories
UNION
SELECT * FROM tbl_categories_custom
) AS p
JOIN tree t ON t.categoryId = p.categoryParentId
)
SELECT *
FROM tree
However, as @trincot showed me in Union two tables with categories in a query that retrieves categories and its parents it can be done much cleaner.
His version over there grabs a category and any category above it.
This one should do it the opposite way; grab any category and any category below it. Which it does. But it seems overcomplicated now that I read his other version.
How to simplify this CTE?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…