I have 2 tables
Categories
id - name - parent 1 - Category A - 0 2 - Category B - 0 3 - Category C - 0 4 - Category D - 0 5 - Subcategory Of 1 - 1 6 - Subcategory Of 5 - 5 7 - Subcategory Of 5 - 5
Product
id - name - category - description 1 - Name - 5 - Description
How to select all products and join main category through sub-categories? Product categories can has only 1 or 2 or 3 or 4 levels (Unknown level).
I use "WITH RECURSIVE" in categories table but can't find the way to combine product table with 1 time query
WITH RECURSIVE category_child AS ( SELECT * FROM categories as c WHERE c.id = 5 UNION ALL SELECT c2.* FROM categories AS c2 JOIN category_child as c3 ON c3.parent_id = c2.id )
What's the best way to do this ?
Expected Result
id - name - category - description - root - sub category id 1 - sub category id 2 - sub category id 3
OR
id - name - category - description - root id - name - category - description - sub category id 1 id - name - category - description - sub category id 2 id - name - category - description - sub category id 3