I need to write a query to perform a search where all results are matched by a category.
The categories have subcategories and they work as a nested set model, and each has a lft and a rgt column.
If cat2
, cat3
and cat4
are childs of cat1
then their .lft
values are between cat1.lft
and cat1.rgt
all categories are stored in a CATEGORIES
table and have an ID
as primary key.
what i need is given a category ID
find all items on ITEMS
table that belong to that category but also all items that belong to category sub-categories.
the query im looking for would be something like this
SELECT i.id, i.name
FROM items AS i, categories AS c
WHERE i.category_lft BETWEEN c.given_cat_id_lft AND c.given_cat_id_rgt
what i mean is i get categories primary key (ID
) but on the query i need to work with their rgt and ltf values
Should I use subqueries or maybe joins? And how should the query be? I really don't have that experience in SQL.