1
我有2个表SQL检索树结构查询
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-S希尔特从产品表
- 其类别为15
- 去类别表,看看那里的categoryID = 15
- 看看highercategoryID如果= 0停止,如果不是再取它的值99
- 在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值,以及如何加入产品在他们的类别中,并且有没有使用大量联接的动态方式?
+10是不够的,谢谢。 – user2490355