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