使用datetime和BETWEEN子句进行SQL查询

时间:2017-06-05 13:38:19

标签: mysql datetime

我有“2017-06-13 00:00:00”到“2017-06-13 23:00:00”的房间位置

我跑了两个问题:

1

SELECT * FROM hs_room_slots_tbl
WHERE hs_room_slots_tbl.from BETWEEN '2017-06-12 22:00:00' AND  '2017-06-13 21:00:00' 
   OR  hs_room_slots_tbl.to BETWEEN '2017-06-13 02:00:00' AND  '2017-06-14 01:00:00'

2

SELECT * FROM hs_room_slots_tbl
WHERE hs_room_slots_tbl.from BETWEEN '2017-06-13 03:00:00' AND  '2017-06-13 08:00:00' 
   OR  hs_room_slots_tbl.to BETWEEN '2017-06-13 07:00:00' AND  '2017-06-13 12:00:00'

第一个查询获取插槽,第二个查询是否应该正确获取插槽?我不知道为什么第二个查询没有获取结果。

编辑:这是记录 enter image description here

1 个答案:

答案 0 :(得分:0)

因为在第二个查询中,您需要from在范围内:

BETWEEN '2017-06-13 03:00:00' AND  '2017-06-13 08:00:00' 

并且它是2017-06-13 00:00:00,所以它不在范围内(数据在小时0,你需要它大于3),所以它不匹配 与to相同,您需要它

BETWEEN '2017-06-13 07:00:00' AND  '2017-06-13 12:00:00'

你在23(' 2017-06-13 23:00:00')有它,它不在范围内。数据为23,范围为07-12

所以第二个查询正常工作,它不需要获取数据