分组依据 - 返回计数为零

时间:2013-05-09 21:28:44

标签: mysql count group-by

我有一个如下所示的查询:

SELECT rank, COUNT(distinct member_id) mcount
FROM my_table
GROUP BY rank
order by
field(rank, 1,2,3,4,5,6,7,8,9,10,0);

它为我提供了一个列表,有时计数结果为0,因此排名可能不会显示,例如:

rank | mcount
1    | 2
3    | 2
4    | 2
5    | 2
6    | 2
7    | 2
8    | 2
9    | 2
10   | 2

正如您所看到的排名20未显示,我希望他们显示0这样的计数:

rank | mcount
1    | 2
2    | 0
3    | 2
4    | 2
5    | 2
6    | 2
7    | 2
8    | 2
9    | 2
10   | 2
0    | 0

我能做些什么来完成这项工作?

1 个答案:

答案 0 :(得分:1)

您需要一个值为0到10的表。由于您包含零,因此通常不能使用AUTO_INCREMENT表,因为默认情况下这些表以1开头。

您可以创建包含这些值的表。例如,以下内容将创建一个值为0到10的表:

CREATE TABLE IF NOT EXISTS ids (
    i TINYINT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY
) ENGINE=InnoDB;

SET sql_mode='NO_AUTO_VALUE_ON_ZERO';

INSERT INTO ids
SELECT 0 UNION
SELECT NULL; -- insert 0 and 1

INSERT INTO ids
SELECT NULL FROM
 ids a
,ids b
,ids c
,ids d
LIMIT 9; -- insert 2 thru 10

或者您可以使用:

   SELECT a.i * 4 + b.i AS i FROM
     (SELECT a.i * 2 + b.i AS i FROM (SELECT 0 AS i UNION SELECT 1) a, (SELECT 0 AS i UNION SELECT 1) b) a,
     (SELECT a.i * 2 + b.i AS i FROM (SELECT 0 AS i UNION SELECT 1) a, (SELECT 0 AS i UNION SELECT 1) b) b
   ORDER BY 1
   LIMIT 11

将返回0到10之间的数字。

使用ids表,您的查询将是:

SELECT ids.i rank, IFNULL(COUNT(distinct my_table.member_id), 0) mcount
FROM ids
INNER JOIN my_table ON my_table.rank = ids.i
GROUP BY ids.i
order by
field(ids.i, 1,2,3,4,5,6,7,8,9,10,0);

或者使用SELECT查询,您的查询将是:

SELECT ids.i rank, IFNULL(COUNT(distinct my_table.member_id), 0) mcount
FROM 
(
SELECT a.i * 4 + b.i AS i FROM
  (SELECT a.i * 2 + b.i AS i FROM (SELECT 0 AS i UNION SELECT 1) a, (SELECT 0 AS i UNION SELECT 1) b) a,
  (SELECT a.i * 2 + b.i AS i FROM (SELECT 0 AS i UNION SELECT 1) a, (SELECT 0 AS i UNION SELECT 1) b) b
ORDER BY 1
LIMIT 11
) ids
INNER JOIN my_table ON my_table.rank = ids.i
GROUP BY ids.i
order by
field(ids.i, 1,2,3,4,5,6,7,8,9,10,0);