Reputation: 1108
I'm working on stock control in my system and i have a table for "locations" of stock in a warehouse. This is the location table.
id location_description_id location_key product_id qty
6 1 1 3 25
7 1 2 4 25
8 1 3 3 20
I'm struggling with getting the location values. For example if there is an order for 40 pieces for product id "3", you can see there is 25 pieces in location_key 1 and 20 pieces in location_key 3
What would be the best way to select the next available location_key when the first one runs out? so in this case the return would be id 6, qty 25 and id 8, qty 15 (totaling my 40)
Upvotes: 1
Views: 130
Reputation: 84
Assuming you have result from query to select all locations where the ordered product is stored. You can do this in php.
Edit: edited the function to also return the quantity to pick from every location.
function findLocations($locations, $orderQty)
{
$resultLocs = array();
$i = 0;
$orderRemainQty = $orderQty;
while ($orderRemainQty != 0) {
$locQty = $locations[$i]['qty'];
If ($orderRemainQty > $locQty){
$locations[$i]['pickUpQty'] = $locQty;
$orderRemainQty -= $locQty;
} else {
$locations[$i]['pickUpQty'] = $orderRemainQty;
$orderRemainQty = 0;
}
$resultLocs[] = $locations[$i];
$i++;
}
return $resultLocs;
}
Upvotes: 1
Reputation: 216
There is a concept called OVER (PARTITION BY id) in SQL server which will result id, qty and we can query again to get proper result.
Its hard to get required response in MySQL but below link will help.
-> https://explainextended.com/2009/03/10/analytic-functions-first_value-last_value-lead-lag/
you should be able to generate output like below and from that you can query sum_all>=40 limit 1;
id location_key product_key qty sum_all
6 1 3 25 25
8 3 3 20 45
Upvotes: 0
Reputation: 43499
Do it on PHP side:
$dbLocations = $db->prepare("SELECT * FROM location WHERE product_id = 3")->queryAll();
$totalOrder = 50;
$leftOrder = $totalOrder;
$locations = [];
while ($leftOrder >= 0) {
$location = array_shift($dbLocations);
if (!empty($location)) {
$leftOrder -= $location['qty'];
$locations[] = $location;
} else {
throw new Exception('Quantity is too big for locations');
}
}
Upvotes: 1