返回PHP中MySQL查询的值

时间:2013-12-18 16:18:32

标签: php mysql

我有一张拿着订单行的表。每个订单号有多个订单行。对于每一行,'diff'列中有一个数字,表示该行是否已完成提供。零或以下,线条完整,1或以上,线条不完整。

我需要输出总订单总数和待处理订单总数。

在一些帮助下,我得到了一个关闭但不会在我的PHP脚本中输出任何结果的SQL查询:

$result = mysql_query("SELECT ord_number, MAX( IF( diff <=0,'COMPLETED','PENDING')) FROM  $tabl GROUP BY (ord_number)");

while($row = mysql_fetch_assoc($result)){
    echo $row['COMPLETED'];
    echo $row['PENDING'];
}

如果我在PHPMySQL中直接运行下面的查询,我得到下面列出的输出:

SELECT ord_number, MAX( IF( diff <=0,  'COMPLETED',  'PENDING' ) ) 
FROM tb_raw_orderfill
GROUP BY (
ord_number
)

输出:

00000P1-OR28622 COMPLETED
00000P1-OR28623 COMPLETED
00000P1-OR28624 COMPLETED
00000P1-OR28625 COMPLETED
00000P1-OR28626 PENDING
00000P1-OR28627 COMPLETED
00000P1-OR28628 COMPLETED
00000P1-OR28629 COMPLETED
00000P1-OR28630 COMPLETED
00000S1-OR02107 PENDING
00000S1-OR02108 COMPLETED
00000S1-OR02109 COMPLETED
00000S1-OR02110 COMPLETED
00000S1-OR02111 PENDING

这些都是正确的结果,几乎就像我需要以某种方式不确定它们一样。 结果应该是

待定:3

完成:11

非常感谢任何帮助。

编辑1 - 样本数据:

Product Code    Quantity Ordered    QT Allocated    Diff    Number  Date    Quantity Supplied To Date   Status
code1   10  0   0   00000P1-OR28621 14/11/2013  10  A
code2   20  0   10  00000P1-OR28621 14/11/2013  10  S
code3   20  0   0   00000P1-OR28621 14/11/2013  20  S
code1   120 0   0   00000P1-OR28621 14/11/2013  120 A
code2   2   0   0   00000P1-OR28622 14/11/2013  2   A
code2   10  0   0   00000P1-OR28623 14/11/2013  10  A
code1   10  0   0   00000P1-OR28623 14/11/2013  10  A
code3   10  0   0   00000P1-OR28623 14/11/2013  10  A

3 个答案:

答案 0 :(得分:1)

如果您只需要已完成/挂单的摘要,我不明白为什么您需要MAX功能。我也不明白为什么你需要使用while循环。

这就是我要做的......

$result = mysql_query("SELECT 
(Select count(ord_number) as completed From $tabl Where diff<=0) as completed, 
(Select count(ord_number) as pending From $tabl Where diff>=1) as pending");

$row = mysql_fetch_assoc($result);
echo $row['completed'];
echo $row['pending'];

我还没有真正尝试过你的例子,但我相信这应该有用。

答案 1 :(得分:0)

SELECT * FROM 
(
    SELECT 
    count(ord_number) AS total,
    MAX(IF(diff <=0,  'COMPLETED',  'PENDING')) AS type
    FROM tb_raw_orderfill
) a
GROUP BY a.type

编辑:使用子查询。

Edit2:此外,你的PHP不起作用的原因是你没有为max()函数指定一个别名,并且没有名为'COMPLETED'或'PENDING'的列。获得有效查询后,使用print_r()查看列名称。

答案 2 :(得分:0)

这是杰西卡回答的更正版本:

SELECT
     a.Status
    ,COUNT( a.ord_number ) AS Total
FROM (
    SELECT
         ord_number
        ,IF( MAX(diff) <= 0, 'COMPLETED', 'PENDING' ) AS Status
    FROM $table
    GROUP BY ord_number
) a
GROUP BY a.Status;

这应该返回两行,如下所示:

Status    | Total
----------|--------
COMPLETED | ####
PENDING   | ####

然后您可以这样阅读结果:

$Completed = 0;
$Pending = 0;

while($row = mysql_fetch_assoc($result)) {
    switch( $row['Status'] ) {
      case "COMPLETED":
          $Completed = $row['Total'];
          break;
      case "PENDING":
          $Pending = $row['Total'];
          break;
    }
}

如果您想要一个包含两个总数的单行,请参阅Itsols的答案。