简体   繁体   English

带有类别和子类别的嵌套类别表

[英]Nested Category table with Category and SubCategory

I guys, 伙计们
I have a Category table with CategoryID (primary key), ParentID (int not null) and Category (nvarchar not null). 我有一个带有CategoryID(主键),ParentID(int不为null)和Category(nvarchar不为null)的Category表。
I´m trying to insert and retrieve in this table Categories with ID CategoryID and SubCategories with ID ParentID. 我正在尝试在此表中插入和检索ID为Category CategoryID的类别以及ID为ParentID的SubCategories。
I´ve been trying the whole week-end with no luck, and hope you can help me. 我一直在整个周末都没有运气,希望您能为我提供帮助。 I´m using MSSQL 2008. 我正在使用MSSQL 2008。
The table structure should look like this: 表结构应如下所示:

-Category1          
        SubCategory1  
        SubCategory2  
    ...  

-Category2  
            SubCategory2  
            SubCategory2  
    ...  

Any help will be very appreciated 任何帮助将不胜感激

Check for Common Table Expressions, those allow you to create "recursive-selects". 检查通用表表达式,这些表达式允许您创建“递归选择”。 http://www.mssqltips.com/sqlservertip/1520/recursive-queries-using-common-table-expressions-cte-in-sql-server/ http://www.mssqltips.com/sqlservertip/1520/recursive-queries-using-common-table-expressions-cte-in-sql-server/

You can use a recursive common table expression: 您可以使用递归公用表表达式:

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

You can use MSDN documentation for the WITH statement to specialize your query 您可以对WITH语句使用MSDN文档来专门化查询

Are you just looking for a simple self join? 您只是在寻找简单的自我加入吗? If so, this should work: 如果是这样,这应该起作用:

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

Or do you need to traverse a whole chain of parents? 还是您需要遍历整个父母链? If so, then the recursive CTE is the better approach. 如果是这样,则递归CTE是更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM