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

Tom*_*Tom -3 php mysql field count

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

 Number     Answer
 0          Y
 0          N
 1          Y
 2          Y
 0          Y
Run Code Online (Sandbox Code Playgroud)

我需要知道字段'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";
Run Code Online (Sandbox Code Playgroud)

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

Tar*_*ryn 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
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo

要通过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);
?>
Run Code Online (Sandbox Code Playgroud)

  • @AmazingDreams我正在使用ANSI标准SQL,因此它可以在所有数据库上使用.:)但MySQL中的语法可以缩写. (5认同)