I have a database with an Adjacency List approach to handle categorization of products in which one product may be found under many categories. Get a look at the following database layout:
cats
id parent title desc
1 0 top top level
2 1 Electronics
3 2 Gaming
4 2 Computers
5 4 Tablets
6 1 Food
7 3 Xbox
products
id title qty
1 ToshibaTV 5
2 I-PAD2 9
3 Laser Pen 24
4 Asus Notebook 5
cats_products
id product_id cat_id
1 2 3
2 2 5
3 1 2
4 3 2
5 4 4
In the above example I need an SQL query that is able to retrieve all the products found in Electronics category and any child category of it with any level (Xbox for example which it is not directly child of Electronics) without repeat of the product that found in more than one category like I-PAD2.
I could able to do this with the help of the application in PHP but I wonder if it is possible to do it using just pure sql in MySQL?
What you’re trying to do is rather difficult using the Adjacency List Model. As @Mike suggested, using a Nested Set Model would make this so much easier. Or alternatively doing it via your php code would even be easier.
However, assuming you know how many parent-child levels there could be (or you can assume there wouldn’t be more than X), you can try something like this. This would be easier to read if MySQL supported CTEs, but unfortunately, it does not. In this example, I’ve gone 4 levels deep — you can get the idea of going deeper.
And here is the SQL Fiddle.
Good luck.