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)
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.
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.
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.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With