mySQL query for selecting children

前端 未结 7 1033
失恋的感觉
失恋的感觉 2020-12-20 05:59

I am not sure if this is possible in mySQL. Here are my tables:-

Categories table:

  • id
  • name
  • parent_id (which points to Categories.id)<
7条回答
  •  醉话见心
    2020-12-20 06:51

    Add a column to the Categories table that will contain the complete comma-delimited tree for each group. Using your example, sub-category Educational would have this as the tree '1,2', where 1 = Toys, 2 = Educational (it includes itself). The next nested level of categories would keep adding to the tree.

    To get all products in a group, you use MySQL's FIND_IN_SET function, like so

    SELECT p.ID 
    FROM Products p INNER JOIN Categories c ON p.category_ID = c.ID
    WHERE FIND_IN_SET(your_category_id, c.tree)
    

    I wouldn't use this method for big tables, as I don't think this query can use an index.

提交回复
热议问题