简体   繁体   中英

Use IF in a WHERE clause in MySQL to order conditions and update a column (of a schedule of shows)

I am building a radio schedule where I want to show the current show or the upcoming show or at last the next day's show. If it returns the next day's show I would like to add somthing to the title like CONCAT_WS(" ", "Don't miss tomorrow:", title) . The schedule is in JSON format so I am using JSON_EXTRACT and TIME_FORMAT to be able to compare values of hours. Here is what currently works, except that it shows the upcoming show or the next day's. Where there are days like "tuesday" it is an example for today and wednesday for tomorrow. The BETWEEN condition and the next one select the current show OR the upcoming show for today. How can I check if none of these apply, and if so select the next day's and update the title?

 SELECT * FROM tableName WHERE visible = 1 AND 
  JSON_UNQUOTE(JSON_EXTRACT(schedule, '$.tuesday.active')) = 1 
  AND 
  ( 
    (
        TIME_FORMAT(NOW(), '%H:%i') BETWEEN 
      TIME_FORMAT(JSON_UNQUOTE(JSON_EXTRACT(schedule, '$.tuesday.time[0]')), '%H:%i') AND 
        TIME_FORMAT(JSON_UNQUOTE(JSON_EXTRACT(schedule, '$.tuesday.time[1]')), '%H:%i')
    ) 
    OR 
    (
        TIME_FORMAT(JSON_UNQUOTE(JSON_EXTRACT(schedule, '$.tuesday.time[0]')), '%H:%i') > TIME_FORMAT(NOW(), '%H:%i') AND 
      TIME_FORMAT(JSON_UNQUOTE(JSON_EXTRACT(schedule, '$.tuesday.time[1]')), '%H:%i') < TIME_FORMAT(NOW(), '%H:%i')
    )
    OR
    (
        id = (SELECT id FROM tableName WHERE visible = 1 AND JSON_UNQUOTE(JSON_EXTRACT(schedule, '$.wednesday.active')) = 1 ORDER BY RAND() LIMIT 1)
    )
  ) 
  LIMIT 1

我删除了第二个OR条件,并添加了具有相同条件的UNION,因此通过将其限制为一个,它将返回第一个选择的第一行,否则返回第二天的

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