SQL Query Inner Join with statement?

时间:2014-03-31 20:21:41

标签: sql sql-server inner-join self-join

刚刚添加了带有注释的SQLFiddle示例:http://sqlfiddle.com/#!3/d1cce

我尝试存档以获取查询中最主要的类别(其中Category.CategoryId = NULL

ITEM TABLE:

  • 1 |标题| 2
  • 1 | TITLE2 | 3

CATEGORY TABLE:

  • 1 |主要类别示例| NULL
  • 2 |子类别示例| 1
  • 3 | SubSubcategory示例| 2

结果必须是:

  • 1 |标题|主要类别示例
  • 2 | TITLE2 |主要类别示例

赞:

select item.id, item.title (MAIN category where CategoryId = NULL) 
from .....

因此,您可以看到我可以将Item.CategoryId设置为SUBSUB类别或SUB类别的类别。

但每次我想在查询中将主要类别作为结果

我怎样才能做到这一点?

再一个让自己更清楚的结果:

  • 1-Item 1-Main 2

表:

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)

1 个答案:

答案 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)

SQL Fiddle demo