1

i'm building a simple inventory system. so i created 3 tables

1:Inventories:id,ownerId,name
    This hold the invenotry name and owner, it gives flexibilty to hv more than 1 inventory for each user !.

2:Inventory_items:id,inventoryId,product,vendor,min_amount
    This hold items details. including item name,supplier, min amount for alarm.

3:Inventory_transaction:id,itemId,inventoryId,userId,Amount,description
    Transactions, Amount is -ve and +ve value

so when i load inventories of a user i do

select id,name from inventories where ownerId=$user->id

after that i loop the inventories id's to fetch items conatined within.

so i do

$ret=[];
foreach($inv as $i){
$ret[$i->id]['name']=$i->name;
$ret[$i->id]['items']= query('select * from inventory_items where inventoryId = $i->id');
}

What i need now to include in the above items query a field that is = to

Select sum(amount) from inventory_transaction where itemId=XXXX and inventoryId=XXXX

so that each item i fetch would include its current stock.

but problem is when i try

select *,
(select sum(amount) from inventory_transaction where itemId=XXXX and inventoryId=XXXX) as stock
 from inventory_items where inventoryId = $i->id'

i cannt reference the itemId nor the inventoryId using mysql

and when i do Join it only return items that have transactions..

so how can i do such command ?

i tried also

SELECT i.*,sum(v.amount) FROM `inventory_items` i,inventory_transactions v where v.itemId=i.id

and it works fine, but it doesnt return 1 Row.. not all items.

and do you think this database design is alright or is there a better method/design that i should follow ?

IS there a way that i can add a field to items table that is dynamically updated with the sum of amount from transaction table ?

thanks alot

4

1 回答 1

1

您需要使用“GROUP BY”来显示每个产品的金额总和,“GROUP BY”返回唯一的列组合,Group BY 通常与 sum() 之类的聚合一起使用来显示每个类别的总数或 max() 来显示每个类别的最高值

而不是选择所有列如果您只需要知道每个供应商每个产品的总金额

SELECT i.product,i.vendor,sum(v.amount) 
FROM `inventory_items` i,inventory_transactions v 
WHERE v.itemId=i.id
GROUP BY product,vendor;

“按产品分组”仅当您需要每个产品的总金额时,无论供应商如何

是的,有一种方法可以自动更新总金额,通过使用我们所说的触发器,去这里了解更多关于触发器的信息

您正在寻找的是“插入后”触发器,在插入后触发器中使用如下语句

Update Inventory_items as i
set i.total_amount = (
Select sum(v.amount) from inventory_transaction v
where v.inventoryID = i.id
);

它会更新每个库存项目的所有库存项目的总量,上面的查询可能更有效,但我会把它留给你:)

于 2013-05-27T08:51:49.187 回答