如何在COUNT操作前检查?

时间:2016-06-07 06:37:44

标签: php mysql count sum

1)我有一个名为“plan_info_upload”的表,如:

site_id site_name   2G_bw   3G_bw   route_path
1       MBCGP1      11      0       abc>bcd>cde
2       BOPBG2      12      22      mnl>khl>jhg
3       BOPCB1      11      0       abc>bcd>khl>bbo
4       BOSBB1      0       25      bops>doc>abc>bcd>jkl

我必须找到多少2g& 3g bw&总计2克&来自routh_path的3g bw的unique_hop。但如果它的2G_bw或3G_bw为零,则不计算它。但我不明白如果在计数之前它的值是0还是如何检查它。

我的代码在这里:

<?php
    $unique_hop=$_POST['unique_hop']; 
    $i = 0;
    $sql4 = "SELECT COUNT(2G_bw) AS no_of_2G, SUM(2G_bw) AS total_2G_bw, COUNT(3G_bw) AS no_of_3G, SUM(3G_bw) AS total_3G_bw FROM plan_info_upload WHERE route_path LIKE '%$unique_hop%'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0)
    {
        while($row = $result->fetch_assoc()) 
        {
            $no_of_2G = $row['no_of_2G'];
            $total_2G_bw = $row['total_2G_bw'];
            $no_of_3G = $row['no_of_3G'];
            $total_3G_bw = $row['total_3G_bw'];
            ?>

            <tr>
                <td><?php echo ++$i;?></td>
                <td><?php echo $unique_hop;?></td>
                <td><?php echo $no_of_2G;?></td>
                <td><?php echo $total_2G_bw;?></td>
                <td><?php echo $no_of_3G;?></td>
                <td><?php echo $total_3G_bw;?></td>
            </tr>
            <?php
        }
    }
?>

从第一张表中,如果我选择unique_hop“abc&gt; bcd”,则3 routh_path有此字符串&amp;数数与数量他们现有的2G_bw&amp; 3G_bw。

我的愿望输出将是:

unique_hop     no_of_2G   total_2G_bw   no_of_3G   total_3G_bw
abc>bcd        2          22            1          25

但输出就是这样:

unique_hop     no_of_2G   total_2G_bw   no_of_3G   total_3G_bw
abc>bcd        3          22            3          25

那么如何在COUNT操作前检查?请任何人帮我解决问题。

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT COUNT(nullif(2G_bw, 0)) AS no_of_2G, SUM(2G_bw) AS total_2G_bw, COUNT(nullif(3G_bw, 0)) AS no_of_3G, SUM(3G_bw) AS total_3G_bw FROM plan_info_upload WHERE route_path LIKE '%$unique_hop%'";