mysql在给定范围内生成一系列数字的最佳方法是什么?
我想到的应用程序是编写一个报表查询,为每个数字返回一行,无论是否有任何数据要报告。最简单形式的示例可能是:
SELECT numbers.num, COUNT(answers.id)
FROM <series of numbers between X and Y> numbers
LEFT JOIN answers ON answers.selection_number = numbers.num
GROUP BY 1
我尝试过创建一个包含大量数字的表,但这似乎是一个糟糕的解决方法。
答案 0 :(得分:2)
首先,创建一个名为ints的表,其中包含从0到9的每个数字的一条记录。
CREATE TABLE ints ( i tinyint );
然后用数据填充该表。
INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
现在,您可以使用以下查询生成一系列数字。
SELECT generator.num, COUNT(answers.id)
FROM (
SELECT a.i*10 + b.i AS num
FROM ints a, ints b
ORDER BY 1
) generator
LEFT JOIN answers ON answers.selection_number = generator.num
WHERE generator.num BETWEEN 18 AND 43
要为生成的数字添加另一个位置值,只需添加更多的ints表连接并相应地调整计算。以下将生成三位数字:
SELECT generator.num, COUNT(answers.id)
FROM (
SELECT a.i*100 + b.i*10 + c.i AS num
FROM ints a, ints b, ints c
ORDER BY 1
) generator
LEFT JOIN answers ON answers.selection_number = generator.num
WHERE generator.num BETWEEN 328 AND 643
答案 1 :(得分:0)
你可以尝试使用numbers byn.num而不是group by 1
SELECT numbers.num, COUNT(answers.id)
FROM numbers
LEFT JOIN answers ON answers.selection_number = numbers.num
WHERE numbers.num between X and Y
GROUP BY numbers.num