2014-03-31 72 views
2

只需添加註釋SQLFiddle例如:http://sqlfiddle.com/#!3/d1cceSQL查詢內部加入聲明?

我試圖存檔獲得最主要的類別查詢(其中Category.CategoryId = NULL

項目表:

  • 1 | TITLE | 2
  • 1 | TITLE2 | 3

類別表:

  • 1 | Maincategory示例| NULL
  • 2 |子類別示例| 1
  • 3 | SubSubcategory示例| 2

其結果必然是:

  • 1 | TITLE |主要類別示例
  • 2 | TITLE2 | Maincategory例如

像:

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

因此,大家可以看到我可以Item.CategoryId設置爲一個類別,它是一個SUBSUB類別或子類別。

但我想我的查詢

主要類別,結果每次我怎樣才能做到這一點?

又一個例子的結果讓自己更清楚:

  • 1-1-主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

我不understant您的問題! –

+1

我不確定你想要什麼? – Mack

+0

kkkk !! thx @Mack(我想他想要一個自我加入) –

回答

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

+0

嗨,現在我們進一步。 我唯一需要的是: ITEM TABLE: 1 | TITLE | 2 1 | TITLE2 | 3 分類表: 1 | Maincategory示例| NULL 2 |子類別示例| 1 3 | SubSubcategory示例| 2 結果必須是: 1 | TITLE | Maincategory example 2 | TITLE2 | Maincategory example – user3482630

+0

你可以把它寫入你的問題嗎?閱讀評論太難了。 – Szymon

+0

剛做完了,很難爲我解釋,但我正在努力做到最好。對不起,我的解釋。 – user3482630