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)
I use the above table to map all the categories and sub-categories.
Products table:
- id
- name
- category_id
The category_id in the Products table points to the sub-category id in which it belongs.
e.g. If I have Toys > Educational > ABC where ABC is product, Toys is Category and Educational is sub Category, then ABC will have category_id as 2.
Now the problem is that I want to use a SQL query to display all the products (in all the sub-categories and their sub-categories.. n level) for a particular category.
e.g.:
select * from categories,products where category.name = 'Toys' and ....
The above query should display the products from Educational also and all other sub categories and their subcategories.
Is this possible using a mySQL query? If not what options do I have? I would like to avoid PHP recursion.
Update: Basically I want to display the top 10 products in the main category which I will be doing by adding a hits column to products table.
What I’ve done in previous projects where I’ve needed to do the same thing, I added two new columns.
And then I added a trigger to the table that houses the category information to do the following (all three updates are in the same trigger)…
And then just do a join with your products table on the category ID and do a ‘LIKE ‘%/[CATEGORYID]/%’ ‘. Keep in mind that this was done in MS SQL, but it should be easy enough to translate into a MySQL version.
It might just be compatible enough for a cut and paste (after table and column name change).
Expansion of explanation…
t_categories (as it stands now)…
t_categories (after modification)…
t_categories (after use of the script I gave)
t_products (as you have it now, no modifications)…
Join categories and products (where categories is C, products is P)
Now assuming that the products table was more complete so that there is stuff in each category and no NULLs, you could do a ‘Breadcrumb LIKE ‘%/5/%” to get the last three items of the last table I provided. Notice that it includes the direct items and children of the category (like the Samsung tv). If you want ONLY the specific category items, just do a ‘c.cat = 5’.