如何使用mysql删除嵌套循环

时间:2018-01-26 08:32:39

标签: php mysql

$sqlcmd = "SELECT * FROM inventory WHERE category='$category'";
$temp = mysql_query($sqlcmd);
while ( $value = mysql_fetch_array($temp) ) {
  $sqlcmd = "SELECT SUM(quantity) AS pending 
            FROM withdrawals 
            WHERE item_code='$value[item_code]' 
            AND withdraw_number IN ( 
                SELECT withdraw_number 
                FROM withdrawal_number 
                WHERE is_dispatched=0 AND (series_type='DC' OR series_type='D') )";
  $temp2 = mysql_query($sqlcmd);
  $value2 = mysql_fetch_array($temp2);
}

我尝试改为此,但它并没有给我相同的结果:

$sqlcmd = "SELECT i.item_code, i.item_category, i.item_description, i.quantity, i.reorder_point, SUM(w.quantity) AS pending 
            FROM inventory i, withdrawals w, withdrawal_number wn 
            WHERE i.item_code=w.item_code 
            AND w.withdraw_number=wn.withdraw_number 
            AND i.category='Store' 
            AND wn.is_dispatched=0 
            GROUP BY i.item_code, wn.withdraw_number";
$temp = mysql_query($sqlcmd);
while ( $value = mysql_fetch_array($temp) ) {
}

1 个答案:

答案 0 :(得分:0)

您错过了第二次查询中的series_type支票。如果您想获得零金额,则需要使用LEFT JOIN

并且您不应在withdraw_number中加入GROUP BY,因为您没有在原始查询中对其进行分组,因此它仅用于过滤。

$sqlcmd = "SELECT i.*, IFNULL(pending, 0) AS pending 
        FROM inventory i
        LEFT JOIN (
            SELECT item_code, SUM(pending) AS pending
            FROM withdrawals w
            JOIN (SELECT DISTINCT withdraw_number
                  FROM withdrawal_number 
                  WHERE dispatched = 0 AND series_type IN ('DC', 'D')
            ) AS wn ON w.withdraw_number=wn.withdraw_number
            GROUP BY item_code
        ) AS w ON i.item_code=w.item_code 
        WHERE i.category='$category'";
最里面的子查询中需要

SELECT DISTINCT,以防止将总和乘以具有相同withdraw_number的行数。

您还应该停止使用mysql_*功能。它们已被弃用多年,并在PHP 7中完全删除。您应该使用mysqliPDO,并使用带参数的预准备语句,而不是将变量替换为SQL。