MySQL SELECT列COUNT(名称)WHERE条件GROUP BY列?

时间:2011-08-27 10:07:58

标签: mysql count group-by

嘿,这是我正在使用的SQL语句

$sql = "SELECT number, COUNT(name) FROM people WHERE id='$id' GROUP BY number";  
$result = mysql_query($sql);

while($row = mysql_fetch_array($result)){
$statarray['stat'.$i] = $row['COUNT(name)'];
$i++; }

数字列针对每个名称存储0,1,2或3,因此数组返回总计每个数字的名称数量。这样可以正常工作。

唯一的问题是,如果所有名称都有一个存储的数字1,我​​的数组条目'stat0'不告诉我有多少0,因为它被1的数量所取代(这是因为有数组中没有0,因此第一个输出是1s)..

如何找出有多少名字在其数字栏中有0s 1s 2s和3s,包括什么时候没有?...提前感谢。

1 个答案:

答案 0 :(得分:3)

SELECT  numbers.number ,
        COUNT(name)
FROM    ( SELECT    0 AS number
          UNION ALL
          SELECT    1
          UNION ALL
          SELECT    2
          UNION ALL
          SELECT    3
        ) numbers
        LEFT JOIN people ON people.number = numbers.number AND id='$id' 
GROUP BY numbers.number

或者,如果您有根据评论的永久号码表

SELECT  numbers.number ,
        COUNT(name)
FROM    numbers
        LEFT JOIN people ON people.number = numbers.number
                            AND id = '$id'
WHERE   numbers.number BETWEEN 0 AND 3
GROUP BY numbers.number