获取行直到达到数量

时间:2013-03-02 23:59:40

标签: php mysql

我有一个SQL数据库,我希望获得记录,直到满足客户的数量要求。这就是我的意思。 请求表

Product     Quantity   Price
-----------------------
Apple          10.0      5.00 

这是获取匹配项的SQL查询:

SELECT c.FName,
       p.ProductName,
       s.Description, 
       s.Quantity, 
       s.Price 
FROM requests r
    INNER JOIN sellers s 
        ON r.ProductID = s.ProductID
   INNER JOIN products p 
        ON p.ProductID=s.ProductID 
   INNER JOIN customers c 
        ON c.ID=s.C_ID       
WHERE r.C_ID = 3 AND r.matchType='Price'
ORDER BY s.Price ASC 

结果如下:

     FName   |   ProductName    |     Description                 |  Quantity  |   Price
    --------------------------------------------------------------------------=
 compny1          Apple                    royal apples fm appleco.      5.0          5.00
    daz            Apple                     sweet apples                6.0          5.50
company2         Apple                       Apples yum                   8.0          9.00 

我想通过选择行并更新数据库来显示完整请求的10KG数量,即输出应为:

apples @5kg from compny1 = 5.00
apples @5kg from daz = 5.50
total = 10.50

数据库应该显示“Daz”数量为1.0 KG。但是,我一直都很蠢。我试图做以下事情:

  while ($rows1 = mysql_fetch_assoc($queryQuantity2)){

        if($rows1['Quantity']==$quantityRequested){ //If the first row = 10KG output only this row.
echo $rows1['FName'];
echo $rows1['NameProduct'];
echo $rows1['Quantity'];
echo $rows1['Price'];
}else{
//stuck here check the next rows and see there is 6KG's .. We need 10KG Requested - 5KG from daz(row1) 
//                                                                            -Remaining amount left(i.e.5KG)
//hence, print the output specified above and UPDATE Database where quantity has been reduced by X amount.
}

好的,问题是什么。我需要“弥补”10KG要求的需求。

现在,“最便宜”的方法是按照我所拥有的Asc Price对可用的匹配进行排序。

不,我们可以看到第一行显示'compny1'以5.00英镑卖出5KG ......所以,我们需要10KG因此我们显示第1行.. 接下来,由于我们尚未满足10KG需求(仍需要另外5KG),我们将看第二行。我们看到'daz'卖6KG。但我们只需要5个以上的KG来满足10KG的需求。 因此,我想要做的是...更新表,以便将第一个记录复制到另一个表,第二行更新为1.0kg剩余(6KG-5KG)。因此,向客户展示: 您的10KG可以通过

购买
compny1 5KG@5.00
daz 5KG@5.50
------ 
Total £10.50

所以,这是我的问题。我不知道在满足请求数量之前如何继续检查行。我想我需要某种“计数器”来跟踪添加的数量“到目前为止”,然后检查下一行需要多少。

1 个答案:

答案 0 :(得分:0)

虽然可能有一个简化版本,但这应该非常接近:

Select FName, 
  IF(summedQty>10,Quantity-(summedQty-10),Quantity) Quantity,
  Price
From (
  Select 
    FName, 
    Quantity, 
    Price,
    @qtySum:=IF(@qtySum>10,10000,@qtySum+Quantity) summedQty
  From Results
    Join (Select @qtySum:=0) t
  Order By Price
  ) t
Where summedQty != 10000

我使用10000作为任意值我知道我永远不会打 - 只要确保它高于任何潜在值。在我使用10的任何地方,你都需要用最大值代替。

SQL Fiddle Demo

如果您不想使用任意值,这似乎也可以正常工作:

Select FName, 
  IF(summedQty>10,Quantity-(summedQty-10),Quantity) Quantity,
  Price
From (
  Select 
    FName, 
    Quantity, 
    Price,
    @qtySum:=@qtySum+Quantity summedQty
  From Results
    Join (Select @qtySum:=0) t
  Order By Price
  ) t
Where IF(summedQty>10,Quantity-(summedQty-10),Quantity) > 0

SQL Fiddle Demo

正如我所说,我确信会有变化,但这应该让你朝着正确的方向前进。