从表中选择总产品数和缺货产品数

时间:2018-08-01 10:37:06

标签: mysql sql select count

我要3张桌子:productproduct_to_storestore

product table
id quantity status
1   1       1
2   0       1
3   0       1
4   23      1

product_to_store table
store_id product_id
1        1
2        2
1        3
2        4

store table
id  name
1   store1
2   store2

要查找产品总数,我可以运行查询以获取表产品中启用了产品状态的所有产品。

select count(*) from product where status=1

total             name
2              Store 1
2               store 2

要查找全部缺货产品,可以在加入所有3个表并使用group by store_id之后在查询下面运行:

Select count(*) as outofproducts from product where quantity=0;

结果如下:

outofproducts     name
1                Store 1
1                store 2

但是我想在单个查询中将上述2个结果组合在一起,如下所示:

outofproducts  total  name
1              2      Store 1
1              2      store 2

3 个答案:

答案 0 :(得分:3)

您将使用条件聚合,即对条件求和/计数:

select
  s.name,
  sum(p.quantity > 0) as in_stock,
  sum(p.quantity = 0) as out_of_stock,
  count(*) as total
from store s
join product_to_store ps on ps.store_id = s.id
join product p on p.id = ps.product_id
group by s.name
order by s.name;

这利用了MySQL的true = 1,false =0。如果您不喜欢它,请将sum(p.quantity = 0)替换为sum(case when p.quantity = 0 then 1 else 0 end)count(case when p.quantity = 0 then 1 end)

答案 1 :(得分:2)

您可以从商店表开始查询,以便我们将总行数作为商店表数据。
然后对每个商店使用嵌套查询以获取商品和商品总数

select 
(Select count(*) as outofproducts from product_to_store  ps inner join product p on p.id = ps.product_id where quantity=0 and ps.store_id = s.id  ) as outofproducts ,
(Select count(*) as count from product_to_store  ps inner join product p on p.id = ps.product_id where ps.store_id = s.id  ) as totalCount,
s.name
from store  s 

答案 2 :(得分:0)

您可以加入相关的子查询以进行计数

  select t1.name, t1.outofproducts, t2.total
  from(
      select b.id, b.name , count(*) outofproducts 
      from product_to_store c  
      inner join product a on a.id = c.product_id
      inner  join store b on a.id = c.store_id 
      where a.quantity = 0
      group by  b.id, b.name 
  ) t1 
  inner join (
      select  b.id, b.name , count(*) total
      from product_to_store c 
      inner join product a on a.id = c.product_id
      inner  join store b on a.id = c.store_id 
      group by  b.id, b.name

  ) t2 on t1.id = t2.id