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

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

    Maybe something like:

    select *
    from products
    where products.category_id IN
      (select c2.category_id 
       from categories c1 inner join categories c2 on c1.category_id = c2.parent_id
       where c1.category = 'Processors'
       group by c2.category_id)
    

    [EDIT] If the category depth is greater than one this would form your innermost query. I suspect that you could design a stored procedure that would drill down in the table until the ids returned by the inner query did not have children -- probably better to have an attribute that marks a category as a terminal node in the hierarchy -- then perform the outer query on those ids.

提交回复
热议问题