获取嵌套类别

时间:2016-06-08 15:37:34

标签: sql sql-server sql-server-2012

我真的很感激这方面的一些帮助。我的老师无法帮助我。

无论如何我有3张桌子

tbl_product:

PID | productname
1   | product 1
2   | product 2
3   | product 3
4   | product 4
..

tbl_categories,motherCategory允许我嵌套类别:

CID | categoriename    | motherCategory
1   | electronics      | NULL
2   | clothing         | NULL
3   | Arduino          | 1
4   | Casings, extra's | 3
..

tbl_productInCategory PID和CID分别是tbl_product和tbl_categories中PID和CID的外键。产品可以分配多个类别,因此PID可以在此表中多次出现。

PID | CID
1   | 3
2   | 3
3   | 4
4   | 4

我想选择给定类别中的所有产品+它的子类别。例如,如果我给它参数CID = 1(电子设备),它也应该返回arduino和Casings中的产品,额外的。

我无法弄清楚如何做到这一点,任何帮助或指示都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

类似于递归WITH

with recur AS 
    (
    SELECT CID,motherCategory FROM tbl_categories WHERE CID = @YourId
    UNION ALL
    SELECT r2.CID, r2.motherCategory FROM tbl_categoriesr2 WHERE r2.motherCategory = recur.CID
    )

    SELECT * FROM tbl_product WHERE PID IN (SELECT CID FROM recur)

答案 1 :(得分:0)

你可以像这样使用Common Table Expression:

declare @tbl_product table (
    PID int,
    productname nvarchar(50)
)

insert into @tbl_product(PID, productname)
select 1, 'product 1'
union
select 2, 'product 2'
union
select 3, 'product 3'
union
select 4, 'product 4'
union
select 5, 'product 5'


declare @tbl_categories table (
    CID int,
    categoriename nvarchar(50),
    motherCategory int
)

insert into @tbl_categories(CID, categoriename, motherCategory)
select 1,'electronics', NULL
union
select 2, 'clothing', NULL
union
select 3,  'Arduino', 1
union
select 4, 'Casings, extra''s', 3

declare @tbl_productInCategory table (
    PID int, 
    CID int
)

insert into @tbl_productInCategory(PID, CID)
select 1, 3
union
select 2, 3
union
select 3, 4
union
select 4, 4

-- COMMON TABLE EXPRESSION
;with category_cte (CID, categoriname, motherCategory)
AS
(   
    select CID, categoriename, motherCategory 
    from @tbl_categories 
    where CID = 1 -- THE CID YOU WANT TO USE
    UNION ALL
    select c.CID, c.categoriename, c.motherCategory 
    from @tbl_categories c
    inner join category_cte cte on c.motherCategory = cte.CID
)
select p.*
from @tbl_product p
inner join @tbl_productInCategory pic on p.PID = pic.PID

请注意,在使用CID的SQL中有注释。

相关问题