我有一个带有start_date
字段的事件表,这是一个标准日期时间。我希望选择表中的所有事件,然后将它们分组输出,分别用月份和年份的事件分隔。
我正在使用这个查询:
SELECT Event.id, Event.name, Event.start_date, Event.end_date,
EXTRACT(MONTH FROM `Event`.`start_date`) AS `event_month`,
EXTRACT(YEAR FROM `Event`.`start_date`) AS `event_year`
FROM `my_events` AS `Event`
生成以下$events
数组:(使用CakePHP)
Array
(
[0] => Array
(
[Event] => Array
(
[id] => 1
[name] => Event Name One
[start_date] => 2011-07-03 11:00:00
[end_date] => 2011-07-03 16:00:00
)
[0] => Array
(
[event_month] => 7 // This event occurs in July
[event_year] => 2011
)
)
[1] => Array
(
[Event] => Array
(
[id] => 2
[name] => Event Name Two
[start_date] => 2011-07-09 11:00:00
[end_date] => 2011-07-09 15:00:00
)
[0] => Array
(
[event_month] => 7 // this event occurs in July
[event_year] => 2011
)
)
[2] => Array
(
[Event] => Array
(
[id] => 3
[name] => Event Name Three
[start_date] => 2011-07-09 11:00:00
[end_date] => 2011-07-09 15:00:00
)
[0] => Array
(
[event_month] => 8 // this event occurs in august.
[event_year] => 2011
)
)
我现在希望在这些阵列中循环,并产生如下输出:
七月
- 事件名称一
- 事件名称二
八月
- 事件名称三
我选择使用EXTRACT
SQL函数,因为它似乎是一种非常常见的获取数据的方法。
我认为array_merge
可能是一个选项,但$result = array_merge($event)
似乎没有任何作用。
我走对了吗?还是有更好的方法来实现这一点?
谢谢。
使用分组依据:
select month( event.start_date), year( event.start_date), group_concat( distinct event.name ) from my_events event group by year(event.start_date), month(event.start_date);
您可以使用YEAR()
和MONTH()
或MONTHNAME()
函数,但我认为您不需要GROUP BY
,而是需要ORDER BY
:
SELECT YEAR( Event.start_date ) AS event_year
, MONTH( Event.start_date ) AS event_month
, MONTHNAME( Event.start_date ) AS event_month_name
, Event.id
, Event.name
, Event.start_date,
, Event.end_date
FROM my_events AS Event
WHERE Event.start_date >= '2011-07-01'
AND Event.start_date < '2013-01-01'
ORDER BY Event.start_date ASC
当月份或年份从一行变到下一行时,您可以使用PHP代码中的event_year
和event_month
添加July、August等…和2011标记。