您需要一个包含 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);