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 buildi
Counter from 1 to 1000:
:
select tt.row from
(
SELECT cast( concat(t.0,t2.0,t3.0,t4.0) + 1 As UNSIGNED) as 'row' FROM
(select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t,
(select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3
) tt
order by tt.row
Credits: answer, comment by Seth McCauley below the answer.
If you were using Oracle, 'pipelined functions' would be the way to go. Unfortunately, MySQL has no such construct.
Depending on the scale of the numbers you want sets of, I see two simple ways to go : you either populate a temporary table with just the numbers you need (possibly using memory tables populated by a stored procedure) for a single query or, up front, you build a big table that counts from 1 to 1,000,000 and select bounded regions of it.
There is no sequence number generator (CREATE SEQUENCE) in MySQL. Closest thing is AUTO_INCREMENT
, which can help you construct the table.
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
You could try something like this:
SELECT @rn:=@rn+1 as n
FROM (select @rn:=2)t, `order` rows_1, `order` rows_2 --, rows_n as needed...
LIMIT 4
Where order
is just en example of some table with a reasonably large set of rows.
Edit: The original answer was wrong, and any credit should go to David Poor who provided a working example of the same concept
How big is m?
You could do something like:
create table two select null foo union all select null;
create temporary table seq ( foo int primary key auto_increment ) auto_increment=9 select a.foo from two a, two b, two c, two d;
select * from seq where foo <= 23;
where the auto_increment is set to n and the where clause compares to m and the number of times the two table is repeated is at least ceil(log(m-n+1)/log(2)).
(The non-temporary two table could be omitted by replacing two with (select null foo union all select null) in the create temporary table seq.)