简体   繁体   English

MySQL查询日期范围

[英]MySQL querying date range

Here's my database (free rooms in a hotel, simplified) 这是我的数据库(酒店的免费房间,简化)

rooms_available : rooms_available

id  date_available   room_id
================================
1   2013-12-19       2
2   2013-12-20       2
3   2013-12-21       2
4   2013-12-22       2
5   2013-12-23       2
6   2013-12-25       3

rooms : 房间

id  name           minimal_range
================================
2   Apartment A    5
3   Apartment B    1

I want to query all rooms which are available between 2013-12-20 and 2013-12-22 我想查询2013-12-20和2013-12-22之间可用的所有房间

My query is like: 我的查询如下:

select * 
from rooms_available 
where (date='2013-12-20' OR date='2013-12-21' OR date='2013-12-22')

My questions: 我的问题:

  • is there a more comfortable way? 有更舒适的方式吗? when the date range will be like 2 weeks, the query will also be very long (which will take much longer for querying) 当日期范围为2周时,查询也会很长(查询时间会更长)
  • would it be possible to consider minimum ranges - for example: room_id 2 is only available for at least 5 nights (see table "rooms") -> so above query should return no records 是否可以考虑最小范围 - 例如:room_id 2仅适用于至少5晚(见表“房间”) - >所以上面的查询应该不返回任何记录

Thanks 谢谢

date> ='2013-12-20'和date <='2013-12-22'

SELECT * FROM rooms_available WHERE `date_available` BETWEEN "2013-12-20 " AND "2012-03-31"

I didn't test this but it should point you in the right direction especially for the second part of your question about minimal range. 我没有对此进行测试,但它应该指向正确的方向,尤其是关于最小范围的问题的第二部分。

SELECT t1.id as id, t1.date_available as date_available, t1.room_id 
FROM rooms_availble as t1 JOIN rooms as t2 on t1.room_id = t2.id 
WHERE t1.date_available BETWEEN DATE('2013-12-20') AND DATE('2012-03-31') AND
t2.minimal_range <= datediff('2013-12-22', '2012-12-20');

The mysql datediff function will return the number of days between two dates then you can just compare it with the minimal_range from the rooms join table. mysql datediff函数将返回两个日期之间的天数,然后您可以将它与房间连接表中的minimal_range进行比较。 Also you might consider binding the start and end dates to variables so that you only have to write each date once. 您也可以考虑将开始日期和结束日期绑定到变量,这样您只需要编写一次日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM