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

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

    The best solution for this is at the database design stage. Your categories table needs to be a Nested Set. The article Managing Hierarchical Data in MySQL is not that MySQL specific (despite the title), and gives a great overview of the different methods of storing a hierarchy in a database table.

    Executive Summary:

    Nested Sets

    • Selects are easy for any depth
    • Inserts and deletes are hard

    Standard parent_id based hierarchy

    • Selects are based on inner joins (so get hairy fast)
    • Inserts and deletes are easy

    So based on your example, if your hierarchy table was a nested set your query would look something like this:

    SELECT * FROM products 
       INNER JOIN categories ON categories.id = products.category_id 
    WHERE categories.lft > 2 and categories.rgt < 11
    

    the 2 and 11 are the left and right respectively of the Processors record.

提交回复
热议问题