如何将多个查询合并为一个?

时间:2019-09-04 14:25:49

标签: php mysql rgraph

我正在RGraph框架上运行折线图,并且正在使用SELECT COUNT语句来表示被拒绝,接受,批准等。...计算被拒绝或接受的项目数,然后将查询数据转储到数组,但是我正在寻找一种更简单的方法来实现此查询,而不是对每个唯一的行值运行查询,还以这种方式思考是否除了拒绝,接受等以外,我是否还必须遇到其他列数据。不会,我的代码似乎没有很好的可扩展性。请帮助

到目前为止,我正在为每个关键字运行查询,希望我的代码对此进行解释。

最后一个变量是我要输入到RGRAPH的变量,它可以很好地工作,但是,如果行数据发生更改,这不是正确的方法,并且伸缩性也不太好。

 <?php  



    $cxn = mysqli_connect("localhost","root","", "csvimport");

    $query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = 'rejected'";

    $result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));

    $display = mysqli_fetch_array($result);

    $rejected = $display[0];

    //echo $rejected;

    $query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = 
              'accepted'";

    $result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));

    $display = mysqli_fetch_array($result);

    $accepted = $display[0];

    //echo $accepted;


    $query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = '-'";

    $result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));

    $display = mysqli_fetch_array($result);

    $dash = $display[0];

    //echo $dash;


    $query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = 
     'approved'";

    $result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));

    $display = mysqli_fetch_array($result);

    $approved = $display[0];

    //echo $approved;



    $datarray = [$rejected, $accepted, $dash, $approved];

    print_r($datarray);
    $data_string = "[" . join(", ", $datarray) . "]";
    echo "<br>";
    print_r($data_string);

?>

1 个答案:

答案 0 :(得分:2)

您可以只使用GROUP BY并将结论列添加到结果集中,所以

SELECT conclusion, COUNT(*) as total
    FROM table_1 
    WHERE conclusion in ('rejected', 'accepted', '-', 'approved')
    GROUP BY conclusion

然后检索结果集的每一行

$totals = [];
while($row = mysqli_fetch_array($result))  {
    $totals [$row[0]] = [$row[1]];
}

$totals将是一个类似

的数组
array( 'accepted' => 12, 
       'approved' => 20...)

如果您需要所有结论,只需删除WHERE conclusion in行,它将返回所有可能性以及计数。