MYSQL日期范围和时间范围

时间:2014-01-25 09:57:59

标签: mysql

计算传真由Graveyard Shift完成,晚上10点 - 早上7点,

日期和时间在不同的领域

    $stmt = $db -> prepare("SELECT count(*) FROM fax WHERE
                date BETWEEN CURDATE() and CURDATE() + INTERVAL 1 DAY 
                    and time >= '22:00:00' and time <= '7:00:00' 
                        and shift='GY' 
                            and complete=1");                
    $stmt -> execute();
    echo $GY_COMP = $stmt -> fetchColumn();

此查询始终为0,但它有数据。

有人可以帮助我查询吗? 在此先感谢:)

2 个答案:

答案 0 :(得分:4)

我认为问题在于您的时间比较:您使用time >= '22:00:00' and time <= '7:00:00'

有效地过滤了所有内容

希望这会有所帮助:http://sqlfiddle.com/#!2/45108/7/0

SELECT * FROM fax
WHERE date BETWEEN CURDATE() and CURDATE() + INTERVAL 1 DAY 
and
((time >= '22:00' and time <= '23:59')
or
(time >= '0:00' and time <= '7:00'))
and shift='GY' 
and complete=1

答案 1 :(得分:0)

感谢Max的时间比较, 我已经对语法进行了更改

SELECT count(*) FROM fax
    WHERE ((date = CURDATE() and (time >='22:00' and time <= '23:59')) 
           or (date=CURDATE() + INTERVAL 1 DAY and (time >= '00:00' and time <= '7:00'))) 
                  and shift = 'GY'
                           and complete = 1

现在我的问题是换班的范围是今天晚上10点到凌晨7点。

但是我上面的语法在更改日期时仍然出错

帮助在MYSQL中使用IF语句

如果是(选择此项),如果(选择此项) 如何在MYSQL语句中正确使用IF ELSE

SELECT count(*) FROM fax
  IF 
  (date = CURDATE() and (time >='22:00' and time <= '23:59')
     THEN 
       SELECT count(*) FROM fax
       WHERE ((date = CURDATE() and (time >='22:00' and time <= '23:59')) 
       or (date=CURDATE() + INTERVAL 1 DAY and (time >= '00:00' and time <= '7:00'))) 
       and shift = 'GY' and complete = 1
   ELSE IF
   (date = CURDATE() and (time >= '00:00' and time <= '7:00')
          THEN
            SELECT count(*) FROM fax
            WHERE ((date = CURDATE() and (time >= '00:00' and time <= '7:00')) 
             or (date=CURDATE() - INTERVAL 1 DAY and (time >='22:00' and time <= '23:59'))) 
             and shift = 'GY' and complete = 1