如何根据键找到特定列的值之间的差异?

时间:2010-05-29 11:45:05

标签: mysql

我有两张表作为purchase_details和invoice_details

我希望从这两个表的数据中存储每个产品的库存/库存。

purchase_details 的结构。

'pid', 'int(10)'
'product_id', 'int(10)' 
'quantity', 'float(8,2)'
'amount', 'float(12,2)'
'expiry_date', 'date'

invoice_details 的结构。

'invoice_id', 'int(10) unsigned'
'product_id', 'int(10) unsigned'
'quantity', 'float(10,2)'
'price', 'float(12,2)'

我想计算剩余库存的总量 (来自purchase_details的产品总数) - (来自invoice_details的产品总和数量)

两个表的Product_id相同。

产品表由产品数据组成,结构为

'id', 'int(10) unsigned'
'cid', 'int(10) unsigned'
'name', 'varchar(90)'
'selling_price', 'float(10,2)'
'mrp', 'float(10,2)'
'reorder_level', 'bigint(20) unsigned'

invoice_details可能包含也可能没有每个product_id的条目。

我该怎么办?

2 个答案:

答案 0 :(得分:1)

这是我的新答案,已在sqlserver上测试过。我不确定mysql

select pro.id, SUM(pro.quantity - inv.quantity)
from (select sum(p.quantity) as quantity, p.id as id from product p group by p.id) as pro, 
     (select sum(i.quantity) as quantity, i.id as id from invoice i group by i.id) as inv
where inv.id = pro.id
group by pro.id;

答案 1 :(得分:0)

select  ( sum(purchase_details.quantity) - sum(invoice_details.quantity)) as stock  
    from products 
    left outer join purchase_details 
    on products.product_id == purchase_details.product_id
    left outer join invoice_details  
    on  products.product_id  =  invoice_details.product_id 
    group by products.product_id

这将为您提供每种产品的库存,如果您需要某些产品,可以添加您的where语句

select  ( sum(purchase_details.quantity) - sum(invoice_details.quantity)) as stock  
    from products 
    left outer join purchase_details 
    on products.product_id == purchase_details.product_id
    left outer join invoice_details  
    on  products.product_id  =  invoice_details.product_id 
    where products.product_id = 137
    group by products.product_id