MYSQL group_concat和IF

时间:2013-01-13 20:13:04

标签: mysql group-concat

使用以下内容从我的数据库中获取一个日期字段; PS以下是使用连接从日期表中获取日期的更多查询。

SELECT event,event_name,
GROUP_CONCAT(DATE_FORMAT(ed.date,'%b %e') ORDER BY ed.date SEPARATOR ',') as date2 
FROM events ev
LEFT JOIN event_dates ed ON ev.eid=ed.eid
WHERE ev.yr='2013' 
GROUP BY ev.eid

这会生成这个占用大量空间的日期列表。

May 16,May 23,May 30,Jun 6,Jun 20

我希望它看起来像

   May 16,23,30,Jun 6,20

这是我试过的查询。但它不起作用,因为子查询似乎不知道事件ID。猜测我可能需要将其转换为连接??

SELECT DISTINCT ev.event_id, 
GROUP_CONCAT(DISTINCT DATE_FORMAT(race_date,'%a') ORDER BY race_date 
SEPARATOR ',   ')   as date1,

(SELECT GROUP_CONCAT(dm) FROM
 (SELECT CONCAT(
    MONTHNAME(race_date),
    ' ',
    GROUP_CONCAT(DAY(race_date) ORDER BY race_date)
    ) as dm 
FROM event_dates ed1 WHERE ed1.event_id=ev.event_id  
GROUP BY MONTH(race_date))as t) as date2

FROM events ev
JOIN event_dates ed ON ev.event_id = ed.event_id AND ev.race_year = ed.race_year 
GROUP BY event_id

1 个答案:

答案 0 :(得分:2)

SELECT GROUP_CONCAT(d) FROM (
  SELECT    CONCAT(
              MONTHNAME(date),
              ' ',
              GROUP_CONCAT(DAY(date) ORDER BY date)
            ) AS d
  FROM      my_table
  GROUP BY  MONTH(date)
) t