Sounds to me like you have a pretty bad database model. You are talking about recursive queries, and those are always tricky.
You have products and categories right?
Do you have sub categories as well?
To keep it simple you should probably split the categories table into categories and sub categories.
Can the product belong to more than one category or sub category?
If it's only one category then add category_id to your products table, if it is more than one you need to use a bivot table called category_product. The same goes for sub categories, the sub category has a category_id to make it belong to a category, then you use a either a sub_category_id on the product if it only can have one sub category, if nopt you use a pivot between the sub categories and the products called product_sub_category.
I suggest you give this post a read.
https://tray2.se/posts/database-design