刚刚添加了带有注释的SQLFiddle示例:http://sqlfiddle.com/#!3/d1cce
我尝试存档以获取查询中最主要的类别(其中Category.CategoryId = NULL
)
ITEM TABLE:
CATEGORY TABLE:
结果必须是:
赞:
select item.id, item.title (MAIN category where CategoryId = NULL)
from .....
因此,您可以看到我可以将Item.CategoryId
设置为SUBSUB类别或SUB类别的类别。
但每次我想在查询中将主要类别作为结果
我怎样才能做到这一点?
再一个让自己更清楚的结果:
表:
create table Item
(
Id INT IDENTITY(1,1) NOT NULL,
CategoryId INT NOT NULL,
Title VARCHAR(80) NOT NULL,
PRIMARY KEY (id)
)
insert into Itemvalues('Item 1', 5)
create table Category
(
Id INT IDENTITY(1,1) NOT NULL,
Title VARCHAR(10) NOT NULL,
CategoryId INT,
PRIMARY KEY (id)
)
insert into Category values('Main item 1', NULL)
insert into Category values('Sub item under Main item 1', 1)
insert into Category values('Main 2', NULL)
insert into Category values(Sub item under 2', 2)
insert into Category values('Subsub item under subitem 2', 4)
答案 0 :(得分:0)
这对于非常适合分层数据结构的公用表表达式来说是一个很好的工作。
;with cte as
(
select Id as ItemId, Title as ItemTitle, CategoryId, 0 as Level
from Item
union all
select cte.ItemId, cte.ItemTitle, c.CategoryId, cte.Level + 1 as Level
from Category c
inner join cte on c.Id = cte.CategoryId
and c.CategoryId is not null
)
select ItemId, ItemTitle, c.Title as CategoryTitle
from cte
inner join Category c on c.Id = cte.CategoryId
where Level = (select Max(Level) from cte as cte1 where cte1.ItemId = cte.ItemId)