-3

我需要计算 mysql 表中 2 个不同字段的某些值,如果可能的话,最好使用一个查询。

 Number     Answer
 0          Y
 0          N
 1          Y
 2          Y
 0          Y

我需要知道“数字”字段中有多少值为 0。

我还需要知道“答案”字段中有多少值为 N。

你能帮我构造查询,还有 PHP 把这些变成一个变量以供使用吗?

IE

 echo "There are ".$number." entries in the number field with a value of 0";
 echo "There are ".$answer." entries in the answer field with a value of N";

感谢您的帮助,在我什至可以继续使用 php.ini 之前,我一直试图弄清楚 mysql 计数。

4

3 回答 3

7

您可以使用带有CASE表达式的聚合函数在单个查询中执行此操作:

select 
  sum(case when number=0 then 1 else 0 end) TotalNumber,
  sum(case when answer='N' then 1 else 0 end) TotalAnswer
from yourtable

请参阅带有演示的 SQL Fiddle

要通过 PHP 获取这些结果,您可以使用mysqli_PDOAPI:

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Sum(CASE 
             WHEN number = 0 THEN 1 
             ELSE 0 
           end) TotalNumber, 
       Sum(CASE 
             WHEN answer = 'N' THEN 1 
             ELSE 0 
           end) TotalAnswer 
FROM   yourtable";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    $row = mysqli_fetch_assoc($result);
    echo "There are " . $row['TotalNumber'] . "entries in the number field with a value of 0";
    echo "There are " . $row['TotalAnswer'] . "entries in the answer field with a value of N";

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>
于 2013-03-01T19:52:36.887 回答
1

试试这个 :

Select SUM(IF(Number = 0, 1, 0)) as count_numbers,
SUM(IF(Answer = 'N', 1, 0)) as count_answers
From table

萨卢多斯 ;)

于 2013-03-01T19:55:40.493 回答
-4
Select count(`Number`) from yourtable where `Number` = 0;
Select count(`Answer`) from yourtable where `Answer` = 'N';
于 2013-03-01T19:51:17.903 回答