1

我有 2 张桌子

Products桌子:

ID     ProductName    Category
0      T-Shirt        15
1      Aqua De Gio    12
2      Jacket         15
3      Hot Water      13

Categories桌子:

categoryID catagoryName       highercategoryID
8          Fragnance          0
99         Clothing           0
15         Armani Clothing    99
12         Armani Fragnance   8
102        Davidoff Fragnance 8

预期结果

ID     ProductName    Category  CategoryTree 
0      T-Shirt        15        Clothing > Armani Cloting
1      Aqua De Gio    12        Fragnance > Armani Fragnance
2      Jacket         15        Clothing > Armani Cloting
3      Hot Water      13        Fragnance > Davidoff Fragnance

例如,从产品表中取出 T 恤

  1. 它的类别是 15。
  2. 转到类别表并查看 categoryID=15 的位置
  3. 查看highercategoryID,如果其= 0 停止,如果不是,则取其值99
  4. 在 categoryID 列中查找 99,更高的类别现在是 0 所以停止。基于上述我需要得到“服装>阿玛尼服装”。

我是 SQL 查询的新手,这是我的第一次尝试

select  
    x.*,
    x.p1 + isnull((' > ' + x.c1), '') + isnull((' > ' + x.c2), '') as CategoryTree 
from 
    (select 
         RP.categoryid as catid,
         RP.catagoryName    as p1,
         R1.catagoryName    as c1,
         R2.catagoryName    as c2
     from 
         categories as RP
     left outer join 
         categories as R1 on R1.highercategoryid = RP.categoryid
     left outer join 
         categories as R2 on R2.highercategoryid = R1.categoryid 
     left outer join 
         categories as R3 on R3.highercategoryid = R2.categoryid 
     where 
         RP.highercategoryid != 0 ) x 

我不知道当我在更高的类别中找到 0 值时如何停止加入,以及如何加入他们的类别上的产品,有没有不使用大量加入的动态方式?

4

1 回答 1

4

它是这样的:

With CTE (CatID, CatName, HigherCatID) AS
(
  SELECT categoryID, CAST(catagoryName AS VARCHAR(1000)), highercategoryID
  FROM CATEGORIES
  UNION ALL
  SELECT C.categoryID, CAST(CTE.CatName + ' > ' + C.catagoryName AS VARCHAR(1000)), CTE.HigherCatID
  FROM CATEGORIES C
  INNER JOIN CTE ON C.HigherCategoryID = CTE.CatID
)
SELECT P.ID, P.ProductName, Cte.CatID, CTE.CatName
FROM CTE INNER JOIN PRODUCTS P
ON (CatID = P.Category)
WHERE CTE.HigherCatID=0 

你有一个SQLFiddle Here

于 2013-06-29T13:50:16.987 回答