2013-03-01 72 views
-3

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

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

我需要知道在外地“数”有多少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"; 

感谢您的帮助,我卡在试图找出MySQL的计数之前我甚至可以移动到PHP。

+1

[你尝试过什么(http://whathaveyoutried.com)? SO不是“给我”或“我需要”的网站。它基于用户的问题提供信息。我们需要努力帮助。 – UnholyRanger 2013-03-01 19:53:25

+0

haz u sql ............ – Drewdin 2013-03-01 20:21:22

回答

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

更容易使用SUM(IF(number = 0,1,0))AS TotalNumber' – AmazingDreams 2013-03-01 19:53:33

+5

@AmazingDreams我使用ANSI标准SQL,因此它可以用于所有数据库。 :)但是MySQL中的语法可以缩写。 – Taryn 2013-03-01 19:54:05

+0

有趣的是,我如何获取2个结果? – Tom 2013-03-01 20:10:52

-4
Select count(`Number`) from yourtable where `Number` = 0; 
Select count(`Answer`) from yourtable where `Answer` = 'N'; 
+2

不,这里充满了错误。 – Jeremy1026 2013-03-01 20:00:47

+0

谜语我,谜那个,伯爵从哪里来? – Kermit 2013-03-01 20:03:26

+0

对不起,我更新了我的帖子。 – 2013-03-01 22:45:18

1

试试这个:

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

Saludos;)