1

I have 2 tables: categories and items.

table: categories

id | parent_id | name
------------------------------
1  | 0         | drinks
2  | 1         | soft drinks
3  | 1         | beer

and

table: items

id | category_id | name
----------------------------
1  | 1           | water
2  | 2           | coca cola
3  | 2           | pepsi cola
4  | 3           | stella artois

What I want to do? I want to count all the items in a category or in a subcategory of that category.

So if I select for the category "drinks" I want to count all the items in the category "drinks" but also all the items in the subcategories "soft drinks" and "beer".

I think it has something to do with a left join but I cannot figure it out.

Thanks in advance!

Sam Leurs
  • 480
  • 4
  • 20

1 Answers1

0

I think this will work.

select c.name,
       (select count(*)
          from items i
         where i.category_id in (select c2.id
                                   from category c2
                                  where c.id in (c2.id, c2.parent_id)
       ) as total
  from category c

This should produce:

name        | total
-------------------
drinks      | 4
soft drinks | 2
beer        | 1
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77