首页 文章

带有Category和SubCategory的嵌套类别表

提问于
浏览
1

我们,
我有一个Category表,其中包含CategoryID(主键),ParentID(int not null)和Category(nvarchar not null) .
我试图在此表中插入和检索ID为CategoryID的类别和具有ID ParentID的SubCategories .
我一直在尝试整个周末没有运气,希望你能帮助我 . 我正在使用MSSQL 2008 .
表结构应如下所示:

-Category1          
        SubCategory1  
        SubCategory2  
    ...  

-Category2  
            SubCategory2  
            SubCategory2  
    ...

任何帮助将非常感激

3 回答

  • 0
  • 0

    您可以使用递归公用表表达式:

    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
    

    您可以使用MSDN documentation作为 WITH 语句来专门化您的查询

  • 0

    你只是在寻找一个简单的自我加入吗?如果是这样,这应该工作:

    select parent.category, subcat.category as subcategory
    from Category subcat join
         Category parent
         on subscat.parentid = parent.categoryid
    

    或者你需要遍历整个父母链?如果是这样,那么递归CTE是更好的方法 .

相关问题