最有效的方法来计算包含某些单元格值的结果集中的行数

时间:2016-02-24 11:11:43

标签: php mysql loops

我正在寻找一种方法来计算包含某些单元格值的结果集中的行数。我想避免使用多个查询和数组。

 $fetch_desktops = mysql_query(
     "SELECT 
       ID, 
       description, 
       site, 
       location, 
       user, 
       status, 
       company, 
       MAX(baseline)  
     FROM 
       items 
     WHERE 
       type LIKE 'Desktop' AND isactivebaseline='Yes'  
     GROUP BY ck_config_item ORDER BY ID DESC;"
 );

我想计算数组中有多少结果的状态为“在线”,以及有多少结果的状态为“离线”。有了这些信息,我将创建一个列表,列出哪些桌面在线和离线。

例如:

在线桌面 - 40

桌面离线 - 20

我可以使用任何特定的PHP / Mysql函数来执行此操作吗?我试图避免使用 MySQL_num_rows ,因为我需要使用多个查询。

提前致谢

3 个答案:

答案 0 :(得分:1)

如果您不能使用多个查询,可以尝试while()循环:

$counter = 0;
$total = 0;
while($row = mysql_fetch_object($fetch_desktops)){
     $status = $row -> status;
     if($status == "online"){
        $counter++;
     }
     $total++;
}
// $counter now holds the count of online desktops, $total holds the total of
//desktops in DB, and the offline count can be done as $total - $counter

答案 1 :(得分:0)

你试试这个Sql

SELECT  
SUM(IF(type='Desktop',IF(isactivebaseline='Yes',1,0),0)) Desktops online,
SUM(IF(type='Desktop',IF(isactivebaseline !='Yes',1,0),0)) Desktops offline 
FROM items     GROUP BY ck_config_item ORDER BY ID DESC

答案 2 :(得分:0)

试试这个:

SELECT X.*, Y.count from
(SELECT 
       ID, 
       description, 
       site, 
       location, 
       user, 
       status, 
       company, 
       MAX(baseline)  
     FROM 
       items 
     WHERE 
       type LIKE 'Desktop' AND isactivebaseline='Yes'  
     GROUP BY ck_config_item ORDER BY ID DESC) X,
(SELECT 
       status, COUNT(*) count
     FROM 
       items 
     WHERE 
       type LIKE 'Desktop' AND isactivebaseline='Yes'  
     GROUP BY status) Y     
where X.status=Y.status;