MySQL - 生成xx行的计数器

时间:2011-12-13 12:11:34

标签: mysql

我只想为每个行生成带有数字的xx行,类似于:

SELECT 1 TO 50

结果集包含50行,从1到50

感谢

3 个答案:

答案 0 :(得分:1)

最简单的方法: -

select 1 union
select 2 union
select 3 union
select 4 union
...
select 50;

或者,您可以考虑编写程序或用户定义的函数

答案 1 :(得分:1)

使用存储过程:

delimiter #

create procedure my_counter(lower_bound INT, upper_bound INT)
begin

declare v_max int unsigned default upper_bound;
declare v_counter int unsigned default lower_bound;

CREATE TABLE temp_my_counter (id int);

   while v_counter <= v_max do
    INSERT INTO temp_my_counter SELECT v_counter;   
    set v_counter=v_counter+1;
  end while;

SELECT temp_my_counter.id FROM temp_my_counter;    
DROP TABLE temp_my_counter;

end #    
delimiter ;

然后call my_counter(2, 5);将返回

2
3
4
5

答案 2 :(得分:0)

你可以试试这个:

select @count := @count + 1
from (select @count := 0) count
cross join (select 1 from information_schema.TABLES limit 10) as ten
cross join (select 1 from information_schema.TABLES limit 10) as hundred
cross join (select 1 from information_schema.TABLES limit 10) as thousand
cross join (select 1 from information_schema.TABLES limit 10) as ten_thousand
limit 50;

或者这(更快):

select @count := @count + 1
from (select @count := 0) count
cross join (select 1 union all select 1) as two
cross join (select 1 union all select 1) as four
cross join (select 1 union all select 1) as eight
cross join (select 1 union all select 1) as sixteen
cross join (select 1 union all select 1) as thirty_two
cross join (select 1 union all select 1) as sixty_four
cross join (select 1 union all select 1) as one_two_eight
cross join (select 1 union all select 1) as two_five_six
cross join (select 1 union all select 1) as five_twelve
cross join (select 1 union all select 1) as one_thousand_twenty_four
limit 50;