2013-03-01 70 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;)

相關問題