Denne løsning bruger ingen loops, procedurer eller midlertidige tabeller . Underforespørgslen genererer datoer for de sidste 10.000 dage og kan forlænges til at gå så langt tilbage eller frem, som du ønsker.
select a.Date
from (
select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a) + (1000 * d.a) ) DAY as Date
from (select 0 as a 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) as a
cross join (select 0 as a 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) as b
cross join (select 0 as a 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) as c
cross join (select 0 as a 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) as d
) a
where a.Date between '2010-01-20' and '2010-01-24'
Output:
Date
----------
2010-01-24
2010-01-23
2010-01-22
2010-01-21
2010-01-20
Bemærkninger om ydeevne
Test det her , ydeevnen er overraskende god:ovenstående forespørgsel tager 0,0009 sek.
Hvis vi udvider underforespørgslen til at generere ca. 100.000 numre (og dermed ca. 274 års datoer), kører den på 0,0458 sek.
Dette er i øvrigt en meget bærbar teknik, der fungerer med de fleste databaser med mindre justeringer.
SQL Fiddle-eksempel returnerer 1.000 dage