获取数量Mysql

时间:2015-01-29 15:38:50

标签: mysql

QUERY 1(第一张表 - 存入)

select sum(s.liquid_quantity) as 'stock in total' from stockin_detail s 
left join reagent r on r.id = s.reagent_id group by r.name

QUERY 2(第二张表 - 库存结束)

select sum(t.consumption)as 'stock out total' ,r.name from stock_out s 
inner join test_consumption t on s.consumption_id = t.id 
inner join reagent r on r.id = t.reagent_id group by r.name 

QUERY 1

stock in  |r.name     
100       |Reagent2                 
100       |Reagent3

QUERY 2

stock out  |r.name     
40         |Reagent2                 
20         |Reagent3

我尝试这样做,但它不会减去因为每个嵌套的select语句返回多个列'由group by引起的错误消息。 我也尝试删除该组,但最终梳理了两个不同的股票,然后减去。

SELECT QUERY1 – QUERY2 as ‘current stocks’

预期出现

current stock|r.name  
60           |Reagent2                 
80           |Reagent3

1 个答案:

答案 0 :(得分:0)

为什么不将两个查询转储到内联视图中,然后将它们连接在一起?

这样的事情会让你前进。内联视图别名'i'是库存和内联视图别名'o'是库存:

select i.name,i.in-ifnull(o.out,0) as 'current stock'
from
 (
  select sum(s.liquid_quantity) as in,r.name 
  from stockin_detail s 
  left join reagent r on r.id = s.reagent_id 
  group by r.name
 ) i
 left outer join
 (
  select sum(t.consumption)as 'out' ,r.name from stock_out s 
  inner join test_consumption t on s.consumption_id = t.id 
  inner join reagent r on r.id = t.reagent_id 
  group by r.name
 ) o on i.name = o.name;