Order by day_of_week in MySQL

后端 未结 10 2150
一向
一向 2020-12-14 04:15

How can I order the mysql result by varchar column that contains day of week name?

Note that MONDAY should goes first, not SUNDAY.

10条回答
  •  旧巷少年郎
    2020-12-14 04:56

    I realise that this is an old thread, but as it comes to the top of google for certain search times I will use it to share my approach.

    I wanted the same result as the original question, but in addition I wanted the ordering of the results starting from the current day of the week and then progressing through the rest of the days.

    I created a separate table, in which the days were listed over a fortnight, so that no matter which day you started from you could run through a sequence of 7 days.

    CREATE TABLE IF NOT EXISTS `Weekdays` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(50) NOT NULL DEFAULT '',
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
    
    INSERT INTO `Weekdays` (`id`, `name`) VALUES
    (1, 'Monday'),
    (2, 'Tuesday'),
    (3, 'Wednesday'),
    (4, 'Thursday'),
    (5, 'Friday'),
    (6, 'Saturday'),
    (7, 'Sunday'),
    (8, 'Monday'),
    (9, 'Tuesday'),
    (10, 'Wednesday'),
    (11, 'Thursday'),
    (12, 'Friday'),
    (13, 'Saturday'),
    (14, 'Sunday');
    

    I then ran the query with a variable that determined the start point in sequence and used a join to get the order number for the days. For example to start the listing at Wednesday, I do the following:

    SELECT @startnum := MIN(id) FROM Weekdays WHERE name='Wednesday';
    SELECT * FROM Events INNER JOIN ( SELECT id as weekdaynum, name as dayname FROM Weekdays WHERE id>(@startnum-1) AND id<(@startnum+7) ) AS s2 ON s2.dayname=Events.day ORDER BY weekdaynum;
    

    I hope this helps someone who stumbles onto this post.

提交回复
热议问题