哪种方法可以根据MySQL表数据减少变量?

Hello StackOverflow community,

first I want to explain that I posted this problem yesterday, but recognized that people don't really understand what the problem is. So I deleted my question and questions and answers for a clearer explanation. If this is not allowed, I am sorry and never do this again.

I have a table called 'orders', let say for candies. Candy merchants can bid and ask for candies for different prices and package sizes.

It can happen that I have two candy-packages (package 1 has 10 candies and package 2 has 11 candies) for the total amount of 21 candies merchants are offering. Now there is another party (called C) who wants to buy 25 candies. Of course this are 4 candies to much so we want to clear as good as possible and calculate 25 candies - 21 candies and the C has a rest of 4 candies I add to my table until the next supplement. This means that I delete package 1 and package 2 after I calculated (25 - 10 - 11) and insert the new value which is 4 (you remember, 25 - 10 - 11).

For this I want to create an algorithm/script. This says, in very simplified pseudocode:

WHILE-loop initiation
IF ($candy_demand_new_offer > $candy_supply_most_recent_row)
{
$candy_demand_new_offer = $candy_demand_new_offer - $candy_supply_most_recent_row;
DELETE $candy_supply_most_recent_row;
INSERT $candy_demand_new_offer;
}

After this would follow some else ifs for the case that demand is lower than supply. But what I get are two new entries. This entries are 15 and 4 because the script first calculates (25 - 10 = 15) and (15 - 11 = 4). Of course my INSERT is the problem, but I can't leave it blank. Because when there is no other recent supply I must insert the rest of the candy demand into the table. But not showing every single step, but the final result.

Now how can I do this? Maybe I got mad or the problem is more complicated than I thought.

Thanks for any help and hope you understand my problem description. If not, please tell me and I learn to get better.

Psuedo-code answer:

while ($candies_needed > 0 && $row = fetch) {
    if ($candies_needed >= $row['candies_available']) {
        $candies_needed -= $row['candies_available'];
        DELETE this row from inventory table;
    } else {
        UPDATE this row in inventory table SET candies_available = candies_available - $candies_needed;
        $candies_needed = 0;
    }
}
if ($candies_needed > 0) { // Haven't fullfilled the entire order
    INSERT $candies_needed into order table;
}