如何创建MySQL函数以输出值为1到给定数字的查询?

时间:2016-12-18 06:23:58

标签: mysql sql

我对MySQL有点新意。我正在尝试创建一个mysql函数,该函数将生成并输出一个查询,其中包含从1到给定数字的值的单个列。

该功能的开始如下,

create function get_NumberSequence (n)

假设我将该函数称为

select get_NumberSequence(5);

我应该得到如下的输出。

Sequence
--------
  1 
  2 
  3
  4
  5

我尝试了一种方法来组合和存储查询,例如

@num:=(select 1 as Sequence)

@num:=@num union (select 2 as Sequence)

这对我没有用。

1 个答案:

答案 0 :(得分:0)

这是输入号码l_input_number < 10^4(10000)的情况。

您可以使用较大的输入数字

更改查询
SELECT @row := @row + 1 as sequence 
FROM 
    (select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t,
    (select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t2, 
    (select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t3, 
    (select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t4, 
    (SELECT @row:=0) t_init
LIMIT 17;  --LIMIT l_input_number;

并为输入数字范围的每个查询使用IF ELSE STATEMENT以获得更好的效果

IF l_input_number < 1000 
THEN --only use query up to t3 
ELSEIF l_input_number < 10000 
THEN --use query up to t4 
ELSEIF l_input_number < 100000 
THEN --use query up to t5 
--etc........
END IF;