user813720
user813720

Reputation: 451

DB architecture for retrieving items stored in child categories from parent categories

Failing to find a solution to this question I was wondering if there was a better way of storing data for this problem.

That db structure allows items to be stored in multiple categories, but doesn't allow easy access to the parent category hierarchy.

What I would like is to have a category relationship such as:

Books 
  > Novels
    > Paperbacks
    > Hardbacks

And have an item stored against Paperbacks for instance that would also show up in Novels and Books. So the 'categories' actually work more like filters than actual categories.

Upvotes: 0

Views: 162

Answers (1)

Eugene Manuilov
Eugene Manuilov

Reputation: 4361

First of all you need to design your category table with usage of Nested Set architecture. With usage of Nested Sets you will easily select whole branch of categories, and then you will be able to select products for these categories.

So the first table will be:

CREATE TABLE categories (
  id int unsigned NOT NULL auto_increment,
  name varchar(255) NOT NULL,
  left int unsigned NOT NULL,
  right int unsigned NOT NULL,
  PRIMARY KEY (id)
);

The second table will be:

CREATE TABLE products (
  id int unsigned NOT NULL auto_increment,
  name varchar(255) NOT NULL,
  PRIMARY KEY (id)
);

And the third table will be:

CREATE TABLE product_categories (
  category_id int unsigned NOT NULL,
  product_id int unsigned NOT NULL,
  PRIMARY KEY (category_id, product_id)
);

Now to select all products for whole branch of categories, you need to use query like this:

SELECT p.*
  FROM categories AS c1
  LEFT JOIN categories AS c2 ON c1.left <= c2.left AND c2.right <= c1.right
  LEFT JOIN product_categories AS pc ON pc.category_id = c2.id
  LEFT JOIN products AS p ON pc.product_id = p.id
 WHERE c1.id = @id

Nested set operations

Add new node

1st step: update already existed categories

UPDATE categories 
   SET right = right + 2, left = IF(left > @right, left + 2, left) 
 WHERE right >= @right

2nd step: insert new category

INSERT INTO categories SET left = @right, right = @right + 1, name = @name

Delete existing node

1st step: delete node

DELETE FROM categories WHERE left >= @left AND right <= @right

2nd step: update else nodes

UPDATE categories 
   SET left = IF(left > @left, left – (@right - @left + 1), left), 
       right = right – (@right - @left + 1) 
 WHERE right > @right

Upvotes: 2

Related Questions