lundi 9 novembre 2015

Categories and Sub Categories Query?

Im trying to set up a database so that I can query it and get all products out for a category and query it for a particular sub category.

I have a products table

id | title | category_id (fk)

And a categories table:

id | title | parent

So if the categories looked like this:

id | title | parent
1  | books | null
2  | crime | 1
3  | spy   | 2
4  | dvd   | null
5  | cd    | null

And products:

id | title | category_id (fk)
1  | 007   | 3
1  | Murder| 2

A product would belong to one category. Above the '007' product belongs to the 'Spy' sub category. 'Murder' belongs to the 'Crime' sub category. Both belong to the parent 'books' category.

How would I query the database to:

  1. Get all products for a sub category (in example for spy I would get '007')

  2. Get all products for a parent category, so if I want all products for books I would get both '007' and 'Murder'.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire