mysql计算已完成列的行数,还计算不完整列的行数?

时间:2014-05-02 10:59:50

标签: php mysql

我正在使用此脚本来计算我的表中已完成列的行数

<?php include 'config.php';

    $q = "SELECT * FROM supplier_session WHERE form1_completed = 'Yes' AND form2_completed = 'Yes' AND form3_completed = 'Yes' AND form4_completed = 'Yes'" or die (mysql_error());
    $result = mysql_query($q);
    $count = mysql_num_rows($result);
?>

<?php echo "(<font color=red>$count</font>)"; ?>

此脚本表示如果&#39; form1_completed,form2_completed,form3_completeed和form4_compelted all =&#39; yes&#39;然后计算行数。

现在我想要做的是,有一个单独的计数,显示不完整的行数,所以请记住,某些行可能只有&#39; form1_completed&#39;作为&#39;是&#39;和&#39; form2_completed&#39;作为&#39; no&#39;。我需要基本上计算任何没有完成所有四列或设置为是的行,所以&#39; form1_complted&#39;,&#39; form2_completed&#39;,&#39; form3_completed&#39;,&# 39; form4_completed&#39;如果这些都不是,那么计算行

有人可以告诉我我该怎么做吗?感谢

2 个答案:

答案 0 :(得分:1)

尝试使用条件聚合:

SELECT sum(form1_completed = 'Yes' AND form2_completed = 'Yes' AND
           form3_completed = 'Yes' AND form4_completed = 'Yes'
          ) as NumAllCompleted,
       sum(not (form1_completed = 'Yes' AND form2_completed = 'Yes' AND
                form3_completed = 'Yes' AND form4_completed = 'Yes'
               )
          ) as NumIncomplete
FROM supplier_session;

这假定已完成的标志永远不会采用NULL值。

注意:将“数组”存储在多列中的值上通常是个坏主意。您应该为每个表单都有一个联结/关联表。这将有一行用于用户/表单组合,以及该表单的状态。它可能还有其他信息,例如表格完成的日期/时间。

答案 1 :(得分:0)

如果字段确实包含NULL值(例如,当他们没有完成表单时,您可以选择所有内容并按如下所示循环它,但我会将字段默认设置为No并使用Gordon Linoff自己回答。

<?php include 'config.php';
        $q = "SELECT * FROM supplier_session" or die (mysql_error());
        $result = mysql_query($q);
        $count = mysql_num_rows($result);
        $completed = 0;
        foreach($result as $check) {
            if(($check['form1_completed'] = 'Yes') && ($check['form2_completed'] = 'Yes') && ($check['form3_completed'] = 'Yes') && ($check['form4_completed'] = 'Yes')) {
             $completed++;
             }
        }

        $count // Total
        $completed // Completed
        $incomplete = $count - $completed; // Not Completed

        echo "(<font color=red>$count</font>)"; 
    ?>