选择查询多个ID

时间:2016-11-01 14:44:50

标签: php mysql

我有2个表:类别和项目。

table: categories

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

table: items

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

我想做什么?我想计算该类别的类别或子类别中的所有项目

因此,如果我选择类别"饮料"我想要计算类别中的所有项目"饮料"还有子类别中的所有项目"软饮料"和"啤酒"。

我认为它与左连接有关,但我无法弄明白。

提前致谢!

1 个答案:

答案 0 :(得分:0)

我认为这会奏效。

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

这应该产生:

name        | total
-------------------
drinks      | 4
soft drinks | 2
beer        | 1
相关问题