如何group_concat与那种情况下的条件一样

时间:2012-10-05 11:30:12

标签: mysql group-concat

我有表(mysql 5.5 INNODB):样本小数据+剪切不相关列的问题 - 真实数据巨大(会议表中超过10,000,000行)

INPUT:

day:

day_id(primary key)|sunday|monday|tuesday|wensday|thursday|friday|saturday
---------------------------------------------------------------------------
60                 |1     |1     |1      |1      |1       |1    |1
74                 |0     |1     |0      |0      |0       |0     |0
98                 |0     |0     |0      |0      |0       |0     |0
..etc......................................................................

meeting:

day_id(foreign key)|time    |type
----------------------------------
60                 |20:09:00|1
98                 |07:00:00|1
74                 |22:01:00|4
98                 |10:00:00|1
60                 |23:09:00|2
98                 |06:00:00|2
74                 |21:04:00|6
98                 |08:00:00|6
.....etc.....................

输出:

sunday_times          |monday_times                           |....etc
-------------------------------------------------------------------------------------------------
20:09:00,etc...       | 20:09:00,etc..   |
................etc..............................................................................

我觉得这样的事情(但我是sql soo的新手,我不知道它是好的还是合法的)

 SELECT 
   GROUP_CONCAT(time where day.sunday=1 ORDER BY time) as sunday_times, 
   GROUP_CONCAT(time where day.monday=1 ORDER BY time) as monday_times,  
   etc..
 FROM day
 JOIN meeting ON meeting.day_id=day.day_id
 GROUP BY type

1 个答案:

答案 0 :(得分:7)

您的语法很接近,您需要在CASE内使用GROUP_CONCAT()语句:

SELECT 
   GROUP_CONCAT(case when day.sunday=1 then time end order by time) as sunday_times, 
   GROUP_CONCAT(case when day.monday=1 then time end order by time) as monday_times
 FROM day
 JOIN meeting ON meeting.day_id=day.day_id
GROUP BY type

请参阅SQL Fiddle With Demo