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

前端 未结 9 1639
再見小時候
再見小時候 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:24

    Looks like a job for a Common Table Expression.. something along the lines of:

    with catCTE (catid, parentid)
    as
    (
    select cat.catid, cat.catparentid from cat where cat.name = 'Processors'
    UNION ALL
    select cat.catid, cat.catparentid from cat inner join catCTE on cat.catparentid=catcte.catid
    )
    select distinct * from catCTE
    

    That should select the category whose name is 'Processors' and any of it's descendents, should be able to use that in an IN clause to pull back the products.

提交回复
热议问题