Hierarchical Data in MySQL

后端 未结 8 1622
南笙
南笙 2020-12-04 22:57

I\'ve got a sort of tree like thing going on in my MySQL database.

I have a database that has categories, and each category has a subcat. I\'m keeping all the catego

8条回答
  •  臣服心动
    2020-12-04 23:35

    I'm assuming you know how to get the ID number and that's not the point of the question. Also, parent_id should also be a FK referencing id, and I would use NULL for the topmost layer, not 0.

    If your top-most categories have at most one level of sub-category, you can use this query to get all Toys:

    SELECT *
    FROM items
    WHERE items.category_id IN (SELECT id FROM categories
                                WHERE categories.parent_id = 1
                                OR categories.id = 1);
    

    If your categories can have nested sub-categories, you'll have to use a stored procedure and call it recursively. Pseudocode:

    Procedure getItemsInCategory
    Input: @category_id integer
    Output: items rows
    {
        For each item in (SELECT *
                          FROM items
                          WHERE items.category_id = @category_id):
            return the row;
    
        For each id in (SELECT id 
                        FROM categories
                        WHERE categories.parent_id = @category_id):
            return the rows in getItemsInCategory(id);
    }
    

提交回复
热议问题