mysql 事件每月31日,MySQL-获取发生事件的月份列表

I am working on a PHP application that displays events. It generates a select box that allows visitors to choose a month for which events should be displayed.

My problem is in regard to the select box, which should display not only months on which an event starts or ends, but also months during which an event is still taking place (even if it started months before and ends months later).

Here is what I've got at the moment, it's pretty basic and only returns months on which events start.

SELECT

DISTINCT DATE_FORMAT(start,'%M %Y') as prettydate,

DATE_FORMAT(start,'%m%Y') as monthyear

FROM

`events`

WHERE

start >= NOW()

ORDER BY

start ASC;

How can I also get February & July but also March, April, May & June 2014 in the result if the only event I've got in 2014 starts in February and finishes in July for example?

Thanks in advance for your help!

解决方案

Assuming you don't have any events that span more than 1 year, and using the following start/end dates:

('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');

this query:

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

will return:

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值