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

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

    What you want to find is the transitive closure of the category "parent" relation. I suppose there's no limitation to the category hierarchy depth, so you can't formulate a single SQL query which finds all categories. What I would do (in pseudocode) is this:

    categoriesSet = empty set
    while new.size > 0:
      new = select * from categories where parent in categoriesSet
      categoriesSet = categoriesSet+new
    

    So just keep on querying for children until no more are found. This behaves well in terms of speed unless you have a degenerated hierarchy (say, 1000 categories, each a child of another), or a large number of total categories. In the second case, you could always work with temporary tables to keep data transfer between your app and the database small.

提交回复
热议问题