选择,求和并与PHP和MySQL进行比较

时间:2017-08-10 03:02:13

标签: php mysql select compare

我的MySQL数据库中有两个表:

1名为“stock”

id | product | qty
----------------------
1  |     1      | 15
----------------------
2  |     1      | 20


And the second one named "orders"
id | product | qty | stock_id
----------------------------
1  |    1    |  7  |   1
-----------------------------
2  |    1    |  8  |   1

所以,在注册一个新的“订单”之前,我需要验证哪个“stock.id”有免费产品可以出售,SUM全部存在order.qty并将其减去stock.qty,对于这个例子我是要插入10件ID为1的产品的新订单($ new_order = '10'(件):

  

对于每个stock.id {SUM(orders.qty)为总计|然后验证'total'> = $ new_order | if(total> = $ new_order){select that stock.id}如果不{继续寻找带免费产品的stock.id}}

希望让自己知道,我需要你的帮助,从PHP为该函数构建MySql查询。

更新

我用这个双重查询解决了:

<?
$queryL = "SELECT id,unidades,producto FROM stock WHERE `producto` = '$producto'";
    $resultL = $mysqli->query($queryL);
    /* array asociativo */
    while($rowL = mysqli_fetch_array($resultL, MYSQLI_ASSOC))
    {
        $id_lote = $rowL['id'];
        $unidades = $rowL['unidades'];

    $queryD = "SELECT SUM(cantidad) as total FROM `pedidos` WHERE `lote` = $id_lote";
    $resultD = $mysqli->query($queryD);
    /* array asociativo */

    if($rowD = mysqli_fetch_array($resultD, MYSQLI_ASSOC)){
        $ventas = $rowD['total'];

        $disponible = $unidades - $ventas;

        if($disponible >= $cantidad){ $lote = $id_lote; }

    }
    }
?>

有人可以帮我简化吗?

0 个答案:

没有答案