0

我有一个看起来像这样的查询:

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

我该怎么做才能做到这一点?

4

1 回答 1

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);
于 2013-05-09T22:35:41.763 回答