开发者

MYSQL Order by Day Buried in String

I've got a bunch of rows with a field called "title" who's data looks like this:

Friday  8:00AM - Hunter Arena 2
Wednesday  7:30AM - West Grass Field
Thursday  8:00A开发者_C百科M - Hunter Arena 1
Saturday  8:00AM - Hunter Arena 1
Wednesday  8:00AM - Hunter Arena 2 

I'm looking to order by the day in the week. (Which I assume would involve parsing the string and then doing some sort of date sort) Is this possible with a MYSQL query?

Thanks in advance -J


One option is to creating a holding table (temp, permanent, your choice!) of some kind of your weekdays and their sort weight.

CREATE TEMPORARY TABLE WkDayWeight (weekday varchar(100), orderWeight int); 
INSERT INTO WkDayWeight  (weekday, orderWeight)
   SELECT           'Monday',1
   UNION ALL SELECT 'Tuesday',2 
   UNION ALL SELECT 'Wednesday',3
   UNION ALL SELECT 'Thursday',4
   UNION ALL SELECT 'Friday',5
   UNION ALL SELECT 'Saturday',6
   UNION ALL SELECT 'Sunday',7

Then you could extract the first word from your column (i.e. find the day of week), and JOIN the holding/reference table of weekday sort weights.

SELECT  * 
FROM    MyTable AS m 
INNER JOIN WkDayWeight   AS d 
  ON d.weekday = SUBSTRING_INDEX(m.MyColumn,' ',1) 
ORDER BY d.orderWeight

It's much more preferable to actually have a datetime column to be able to naturally sort by.

Another alternative: you could achieve this another way by creating a user-defined function who could do the same. You could then, with dubious performance, call the UDF in your ORDER BY. The function would find/refer to the weight of the weekday.

  ORDER BY MyWeekdaySortingFunction(m.MyColumn)


Put an inline case/when clause for the order by...

select 
      yt.YourDataColumns
   from 
      YourTable yt
   order by 
      case when "Sunday" = left( yt.Title, 6 ) then 1
           when "Monday" = left( yt,Title, 6 ) then 2
           when "Tuesday" = left( yt,Title, 7 ) then 3
           when "Wednesday" = left( yt,Title, 9 ) then 4
           when "Thursday" = left( yt,Title, 8 ) then 5
           when "Friday" = left( yt,Title, 6 ) then 6
           else 7
      end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜