Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate an integer sequence in MySQL

Tags:

mysql

I need to do a join with a table/result-set/whatever that has the integers n to m inclusive. Is there a trivial way to get that without just building the table?

(BTW what would that type of construct be called, a "Meta query"?)

m-n is bounded to something reasonable ( < 1000's)

like image 402
BCS Avatar asked Nov 20 '08 06:11

BCS


People also ask

Can we create sequence in MySQL?

MySQL does not provide any built-in function to create a sequence for a table's rows or columns. But we can generate it via SQL query.

How do you create a range of two numbers in MySQL?

To generate a range of numbers in MySQL, you can use stored procedure. Firstly, we need to create a table. After that, we will create a stored procedure that generates a range of number from 10 to 1. After that we need to call the stored procedure that fills a range of numbers in the table.

What is a sequence called in MySQL?

In MySQL, a sequence is a list of integers generated in the ascending order i.e., 1,2,3… Many applications need sequences to generate unique numbers mainly for identification e.g., customer ID in CRM, employee numbers in HR, and equipment numbers in the services management system.


2 Answers

I found this solution on the web

SET @row := 0; SELECT @row := @row + 1 as row, t.* FROM some_table t, (SELECT @row := 0) r 

Single query, fast, and does exactly what I wanted: now I can "number" the "selections" found from a complex query with unique numbers starting at 1 and incrementing once for each row in the result.

I think this will also work for the issue listed above: adjust the initial starting value for @row and add a limit clause to set the maximum.

BTW: I think that the "r" is not really needed.

ddsp

like image 151
David Poor Avatar answered Sep 29 '22 23:09

David Poor


The following will return 1..10000 and is not so slow

SELECT @row := @row + 1 AS row FROM  (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 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 2 union all select 3 union all select 4 union all select 5 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 2 union all select 3 union all select 4 union all select 5 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 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4,  (SELECT @row:=0) numbers; 
like image 22
Unreason Avatar answered Sep 29 '22 22:09

Unreason