Select products where the category belongs to any category in the hierarchy

前端 未结 9 1636
再見小時候
再見小時候 2021-02-06 05:39

I have a products table that contains a FK for a category, the Categories table is created in a way that each category can have a parent category, example:

Compu         


        
9条回答
  •  太阳男子
    2021-02-06 06:31

    CREATE TABLE #categories (id INT NOT NULL, parentId INT, [name] NVARCHAR(100))
    INSERT INTO #categories
        SELECT 1, NULL, 'Computers'
        UNION
    SELECT 2, 1, 'Processors'
        UNION
    SELECT 3, 2, 'Intel'
        UNION
    SELECT 4, 2, 'AMD'
        UNION
    SELECT 5, 3, 'Pentium'
        UNION
    SELECT 6, 3, 'Core 2 Duo'
        UNION
    SELECT 7, 4, 'Athlon'
    SELECT * 
        FROM #categories
    DECLARE @id INT
        SET @id = 2
                ; WITH r(id, parentid, [name]) AS (
        SELECT id, parentid, [name] 
            FROM #categories c 
            WHERE id = @id
            UNION ALL
        SELECT c.id, c.parentid, c.[name] 
            FROM #categories c  JOIN r ON c.parentid=r.id
        )
    SELECT * 
        FROM products 
        WHERE p.productd IN
    (SELECT id 
        FROM r)
    DROP TABLE #categories   
    

    The last part of the example isn't actually working if you're running it straight like this. Just remove the select from the products and substitute with a simple SELECT * FROM r

提交回复
热议问题