MySQL: Is it possible to 'fill' a SELECT with values without a table?

You could try something like this

select * from 
    (select 2000 as year union
     select 2001 as year union
     select 2009
    ) as years, 
    (select 1 as month union 
     select 2 as month union 
     select 3 as month union 
     select 4 as month union 
     select 5 as month union 
     select 6 as month union 
     select 7 as month union 
     select 8 as month union 
     select 9 as month
     )
    AS months 
    WHERE year between 2001 AND 2008 OR (year=2000 and month>0) OR (year = 2009 AND month < 4) 
    ORDER by year,month

If at all possible, try to stay away from generating data on the fly. It makes very simple queries ridiculusly complex, but above all: it confuses the optimizer to no end.

If you need a series of integers, use a static table of integers. If you need a series of dates, months or whatever, use a calendar table. Unless you are dealing with some truly extraordinary requirements, a static table is the way to go.

I gave an example on how to create a table of numbers and a minimal calendar table(only dates) in this answer.

If you have those tables in place, it becomes easy to solve your query.

  1. Aggregate the order data to MONTH.
  2. Right join to the table of months (or distinct MONTH from the table of dates)

You could just fill in the missing months after you've done your query in your application logic.

Tags:

Mysql

Date

Select