[英]Nested Category table with Category and SubCategory
伙計們
我有一個帶有CategoryID(主鍵),ParentID(int不為null)和Category(nvarchar不為null)的Category表。
我正在嘗試在此表中插入和檢索ID為Category CategoryID的類別以及ID為ParentID的SubCategories。
我一直在整個周末都沒有運氣,希望您能為我提供幫助。 我正在使用MSSQL 2008。
表結構應如下所示:
-Category1
SubCategory1
SubCategory2
...
-Category2
SubCategory2
SubCategory2
...
任何幫助將不勝感激
您可以使用遞歸公用表表達式:
WITH cteTable(madeUpColA, madeUpColB, Etc) as
(
-- this select statement with the union all is what does the recursive query
SELECT aCol as madeUpColA, bCol as madeUpColB, Etc
from dbo.someTable
UNION ALL
SELECT aCol as madeUpColA, bCol as madeUpColB, Etc
FROM dbo.someTable st
INNER JOIN cteTable as c -- inner join on relationship
ON st.aCol = c.madeUpColA
)
-- this select statement is what retrieves the data from the above query
SELECT madeUpColA, madeUpColB, Etc
FROM cteTable
-- add your other criteria here
您可以對WITH
語句使用MSDN文檔來專門化查詢
您只是在尋找簡單的自我加入嗎? 如果是這樣,這應該起作用:
select parent.category, subcat.category as subcategory
from Category subcat join
Category parent
on subscat.parentid = parent.categoryid
還是您需要遍歷整個父母鏈? 如果是這樣,則遞歸CTE是更好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.