Return a default value if no rows found

前端 未结 3 769
日久生厌
日久生厌 2020-11-29 10:10

I have the following select statement, to grab the next scheduled item for a stream. If there is no matching row, I want it to return a default value. Here\'s the line I\'m

3条回答
  •  心在旅途
    2020-11-29 10:35

    One way to do it

    SELECT IFNULL(MIN(`file`), 'default.webm') `file` 
      FROM `show`, `schedule` 
     WHERE `channel` = 1 AND `start_time` <= UNIX_TIMESTAMP() 
       AND `start_time` > UNIX_TIMESTAMP()-1800 AND `show`.`id` = `schedule`.`file` 
     ORDER BY `start_time` DESC LIMIT 1
    

    Since you return only one row, you can use an aggregate function, in that case MIN(), that ensures that you'll get NULL if no records selected. Then IFNULL() or COALESCE() will do its job.

提交回复
热议问题