【问题标题】:Select count of total products as well as out of stock products from table从表中选择总产品数以及缺货产品数
【发布时间】:2018-08-01 10:37:06
【问题描述】:

我要 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

【问题讨论】:

  • 也添加适当的数据样本,而不仅仅是预期的结果..
  • "但我希望将以上 2 个结果组合成单个查询,如下所示:" 什么两个结果我只看到一个..
  • ""要查找全部产品,我可以运行查询以获取表 product 中产品状态已启用的所有产品。" 什么查询?
  • 添加您的表格架构 .. 表格是如何关联的
  • @scaisEdge 现在检查。我已经添加了。但是没有它也可以理解。

标签: mysql sql select count


【解决方案1】:

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

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)

【讨论】:

    【解决方案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 
    

    【讨论】:

    • 谢谢。您的解决方案也有效,但使用多个选择查询并获取总产品数为 0 的结果。我想要@thorsten 提到的结果。仍然对您的答案投了赞成票。
    【解决方案3】:

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

      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
    

    【讨论】:

    • 此查询用于获取所有产品数据。我想从单个查询中计算单个表中的总产品数和缺货产品数
    猜你喜欢
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多