MySQL计算2个字段中的唯一值

时间:2013-03-01 19:47:54

标签: php mysql count field

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

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

我需要知道该领域有多少' Number'值为0.

我还需要了解该领域有多少人回答'的值为N.

你能帮我构建查询吗,还有PHP把它们变成一个变量供使用吗?

 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之前,我一直试图找出mysql计数。

3 个答案:

答案 0 :(得分: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 with Demo

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

<?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);
?>

答案 1 :(得分:1)

试试这个:

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

Saludos;)

答案 2 :(得分:-4)

Select count(`Number`) from yourtable where `Number` = 0;
Select count(`Answer`) from yourtable where `Answer` = 'N';