php mysql如果总和不工作

时间:2010-07-09 05:25:29

标签: php mysql

trans_id  trans_product  trans_user  trans_date  trans_date2  trans_description  trans_inventory
     13         6              1     1278604284   1278547200                     -1000
      9         5              1     1278601462   1278547200    New Arrival        200
     11         7              1     1278601743   1278547200                        50
     12         6              1     1278601756   1278547200                      5000
$sql = mysql_query("SELECT *, SUM(IF(trans_inventory>0,trans_inventory,0)) as pos "
                  +"FROM site_trans GROUP BY trans_product") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
    $amt_p = $row['pos'];
    $sql2 = mysql_query("SELECT *, SUM(IF(trans_inventory<0,trans_inventory,0)) as neg "
                      + "FROM site_trans GROUP BY trans_product") or die(mysql_error());
    while($row2 = mysql_fetch_array($sql2)) {
        $amt_n = $row2['neg'];
    }

    echo $amt_p; //working
    echo $amt_n; // not working
}

第一个sql查询正在工作($ amt_p)然而第二个是负面的是不工作($ amt_n)任何想法我做错了什么?

3 个答案:

答案 0 :(得分:2)

您为每个产品覆盖$amt_n。我建议将查询组合成这样的东西:

$sql = mysql_query("SELECT *, "
                  + "SUM(IF(trans_inventory>0,trans_inventory,0)) as pos, "
                  + "SUM(IF(trans_inventory<0,trans_inventory,0)) as neg "
                  + "FROM site_trans GROUP BY trans_product") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
    $amt_p = $row['pos'];
    $amt_n = $row['neg'];

    echo $amt_p;
    echo $amt_n;
}

答案 1 :(得分:1)

添加$amt_n = 0以初始化它 将$amt_n = $row2['neg'];更改为$amt_n += $row2['neg'];

问题是你在迭代它时将值归零

你需要为pos和neg

这样做

DC

答案 2 :(得分:0)

不确定为什么它不起作用,但它在我看来你只想要所有正面和负面的trans_inventory行。如何在第一个查询中添加“where trans_inventory&gt; 0”并摆脱有条件的IF hoohah?

SELECT *, SUM(trans_inventory) as pos 
FROM site_trans
WHERE trans_inventory>0
GROUP BY trans_product

“你不工作”究竟是什么意思?你得到什么价值,你期待什么?