假设您没有任何超过 1 年的事件,并使用以下开始/结束日期:
('2012-01-01','2012-01-31'),
('2012-03-01','2012-03-31'),
('2012-05-01','2012-06-01'),
('2012-07-01','2012-07-31'),
('2012-09-01','2012-10-31'),
('2012-11-01','2012-11-30');
这个查询:
SELECT DISTINCT
DISTINCT DATE_FORMAT(e.start + INTERVAL ids.id MONTH,'%M %Y') as prettydate,
DATE_FORMAT(e.start + INTERVAL ids.id MONTH,'%m%Y') as monthyear
FROM
(
SELECT 0 AS id
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
UNION SELECT 10
UNION SELECT 11
) ids,
events e
WHERE
EXTRACT(YEAR_MONTH FROM e.start + INTERVAL ids.id MONTH) <=
EXTRACT(YEAR_MONTH FROM e.end)
ORDER BY
e.start + INTERVAL ids.id MONTH
将返回:
prettydate monthyear
January 2012 012012
March 2012 032012
May 2012 052012
June 2012 062012
July 2012 072012
September 2012 092012
October 2012 102012
November 2012 112012
有关工作示例,请参阅http://sqlfiddle.com/#!2/12b08/3 。