例如,服务器时间为15:00:00。我运行以下查询,但它给我错误的结果。这是我的查询
SELECT
CASE
WHEN TIME(NOW()) BETWEEN '08:00:01' AND '10:00:00'
THEN 1
WHEN TIME(NOW()) BETWEEN '14:00:01' AND '08:00:00'
THEN 2
ELSE 0
END AS IdShift
我的查询出了什么问题?从这种情况下,我的预期结果是2。但是它给了我0
答案 0 :(得分:2)
在BETWEEN
子句中,您必须先指定较低的值,然后再指定较高的值。
因此,您必须将BETWEEN '14:00:01' AND '08:00:00'
更改为BETWEEN '08:00:00' AND '14:00:01'
。
当您想从14:00
到第二天 08:00
时,您必须包括日期。
您可以这样做:
SELECT
CASE
WHEN NOW() BETWEEN CONCAT(CURDATE(), ' 08:00:01') AND CONCAT(CURDATE(), ' 10:00:00')
THEN 1
WHEN NOW() BETWEEN CONCAT(CURDATE(), ' 14:00:01') AND CONCAT(CURDATE() + INTERVAL 1 DAY, ' 08:00:00')
THEN 2
ELSE 0
END AS IdShift
答案 1 :(得分:0)
如另一个答案中所述,对于between
,下界始终是第一个。我不是between
的粉丝,但是您需要分开条件:
SELECT (CASE WHEN TIME(NOW()) BETWEEN '08:00:01' AND '10:00:00'
THEN 1
WHEN TIME(NOW()) BETWEEN '14:00:01' AND '23:59:59'
THEN 2
WHEN TIME(NOW()) BETWEEN '00:00:00' AND '08:00:00'
THEN 2
ELSE 0
END) AS IdShift
或者,用or
来表达这一点:
SELECT (CASE WHEN TIME(NOW()) > '08:00:00' AND TIME(NOW()) <= '10:00:00'
THEN 1
WHEN TIME(NOW()) > '14:00:00' OR TIME(NOW()) < '08:00:00'
THEN 2
ELSE 0
END) AS IdShift
我倾向于将逻辑改变一两分钟并使用几个小时:
(case when hour(now()) >= 8 and hour(now()) < 10
then 1
when hour(now()) >= 14 or hour(now()) < 8
then 2
end)