简体   繁体   English

SQL检索树结构查询

[英]SQL retrieving tree structure query

I have 2 tables 我有2张桌子

Products table: Products表:

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

Categories table: Categories表:

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

Expected result 预期结果

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

For example take the T-Shirt from the products table 例如,从产品表中取出T恤

  1. its category is 15. 它的类别是15。
  2. go for the categories table and see where categoryID=15 转到类别表,看看categoryID = 15的位置
  3. look at the highercategoryID if its = 0 stop, if not then take its value 99 如果它的= 0停止,请查看highercategoryID,如果不是,则取其值99
  4. look for 99 in the categoryID column, the higher category now is 0 so stop. 在categoryID列中查找99,现在更高的类别是0所以停止。 based on the above I need to get "Clothing > Armani Clothing". 基于以上我需要得到“服装>阿玛尼服装”。

I am new to SQL queries and here is my first try 我是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 

I am not sure how to stop the joining when I find the 0 value in the higher category, and how to join the products on their categories, and is there a dynamic way without using a lot of joins? 当我在较高类别中找到0值,以及如何在其类别中加入产品时,我不确定如何停止加入,并且是否存在不使用大量连接的动态方式?

Here it goes: 在这里:

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 

you got a SQLFiddle Here 你有一个SQLFiddle在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM