Question

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

Was it helpful?

Solution

You need to use "GROUP BY" to show the sum of amount per product, "GROUP BY" returns unique column combination, Group BY is usually used with aggregates like sum() to display the total per category or max() to display the topmost value per category

Instead of selecting all columns If you only need to know the total amount per product per vendor

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

"Group by product" only if you need the total amount per product regardless of vendor

Yes there is a way to auto update the sum amount, by using what we call TRIGGERS, go HERE to know more about triggers

What you are looking for is the "after insert" trigger, in the after insert trigger use a statement like

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

which updates the total amount of all inventory items per inventory item, the above query could be more efficient but I'll leave it that to you :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top