简体   繁体   中英

MYSQL: Using DAYNAME() to get data for the nearest date to today

In my mySQL db, I have a column called 'day'. Each training session has a different day - for this example, U12s has one on Tuesday and Thursday. What I want, is to get the data for the closest session (right now, that'd be Tuesday).

SELECT * 
  FROM training 
 WHERE `day` > dayname(now()) 
   AND `group` = 'U12s' 
 ORDER by `day` 
 LIMIT 1

This brings up a result, but it is sorting 'day' alphabetically, so the result is Thursday instead of Tuesday.

I also tried

SELECT * 
  FROM training 
 WHERE `day` > dayofweek(CURDATE()) 
   AND `group` = 'U12s' 
 LIMIT 1

but that brought up no results at all.

Any suggestions?

JorgeCampos' solution & syntax error:

                 SELECT * 
              FROM training 
             WHERE `day` > dayname(now()) 
               AND `group` = 'U12s' 
             ORDER BY CASE when `day` = 'Monday' then 1
                           when `day` = 'Tuesday' then 2
                           when `day` = 'Wednesday' then 3
                           when `day` = 'Thursday' then 4
                           when `day` = 'Friday' then 5
                           when `day` = 'Saturday' then 6
                           else 7 end case
             LIMIT 1

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'case LIMIT 1' at line 11

If your day column is the name of the days and your query is already ok but the order is wrong you just need to convert the day for a value that can be ordered as you need so:

SELECT * 
  FROM training 
 WHERE `day` > dayname(now()) 
   AND `group` = 'U12s' 
 ORDER BY CASE when `day` = 'Monday' then 1
               when `day` = 'Tuesday' then 2
               ....
               when `day` = 'Saturday' then 6
               else 7 end
 LIMIT 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM