我已经阅读了很多关于扁平化父子层次结构的内容,但发现很难实现它。我有一个产品表,我有ChildCategoryDesc和ParentCategoryDesc。在某些情况下,有4个级别的层次结构,我希望在ParentCategoryDesc中看到最高层次结构级别。请参阅下面的代码:
初始代码:
SELECT
ProductID
,cat.categoryDesc AS 'ChildCategoryDesc'
,ISNULL(cat2.categoryDesc,cat.categoryDesc) AS 'ParentCategoryDesc'
FROM dbo.product p
INNER JOIN dbo.category cat ON cat.categoryID = p.categoryID
LEFT JOIN dbo.category cat2 ON cat.parentCategoryID = cat2.CategoryID
我尝试处理层次结构问题:
--Listing 2: Static Query Baased on Joins
WITH C AS
(
SELECT
A.categoryID
,A.categoryID AS A_catid
,B.categoryID AS B_catid
,C.categoryID AS C_catid
,D.categoryID AS D_catid
,( SELECT COUNT(A.categoryID)
FROM (VALUES(A.categoryID),(B.categoryID),(C.categoryID),(D.categoryID)) AS D(categoryID) ) AS lvl
FROM dbo.category AS A
LEFT OUTER JOIN dbo.category AS B
ON A.categoryID = B.categoryID
LEFT OUTER JOIN dbo.category AS C
ON B.categoryID = C.categoryID
LEFT OUTER JOIN dbo.category AS D
ON C.categoryID = D.categoryID
GROUP BY A.categoryID,B.categoryID,C.categoryID,D.categoryID
)
SELECT categoryID, lvl,
CASE 1
WHEN lvl THEN A_catid
WHEN lvl - 1 THEN B_catid
WHEN lvl - 2 THEN C_catid
WHEN lvl - 3 THEN D_catid
END AS level1,
CASE 2
WHEN lvl THEN A_catid
WHEN lvl - 1 THEN B_catid
WHEN lvl - 2 THEN C_catid
END AS level2,
CASE 3
WHEN lvl THEN A_catid
WHEN lvl - 1 THEN B_catid
END AS level3,
CASE 4
WHEN lvl THEN A_catid
END AS level4
FROM C
修改
使用我的初始代码,数据如下所示:
类别编辑中的所有产品最终都会以连衣裙结束,但是使用我当前的代码并不是这样做的。关于parentCategoryID,它只有一个级别。
检查我的初始代码以进行更改
新编辑
我刚刚编写了以下代码,它似乎正在运行,有人可以告诉我这是否具有高性能影响或者可以使用它。
SELECT distinct productDesc
,cat.categoryID
,cat.categoryDesc
,cat.categoryDesc AS 'ChildCategoryDesc'
,CASE
WHEN cat4.categoryDesc IS NOT NULL
THEN cat4.categoryDesc
WHEN cat3.categorydesc IS NOT NULL
THEN cat3.categoryDesc
WHEN cat2.categoryDesc IS NOT NULL
THEN cat2.categoryDesc
ELSE cat.categoryDesc
END AS 'ParentCategoryDesc'
,cat.[ParentCategoryID]
,cat.[ParentCategoryTypeID]
FROM scv_build.dbo.product p
INNER JOIN scv_build.dbo.category cat ON cat.categoryID = p.categoryID
LEFT JOIN dbo.category cat2 ON cat.parentCategoryID = cat2.CategoryID
LEFT JOIN dbo.category cat3 ON cat2.parentCategoryID = cat3.categoryID
LEFT JOIN dbo.category cat4 ON cat3.parentCategoryID = cat4.categoryID