[英]How do I query two dates in mysql where the datefrom is in one column and dateto is in the second column of the same table?
I have a hotel reservation system MySQL database which has a table 'bookings'. 我有一个酒店预订系统MySQL数据库,其中有一个表'bookings'。 The 'bookings' table includes two columns, datefrom (checkin) and dateto (checkout), their data-types are DATE.
“预订”表包括两列,即datefrom(签入)和dateto(签出),其数据类型为DATE。 I need to query the database to show all bookings between two searchable dates.
我需要查询数据库以显示两个可搜索日期之间的所有预订。
The code I have is as follows: 我的代码如下:
SELECT * FROM bookings WHERE datefrom '2018-06-01' AND '2018-06-07';
This returns any booking where the start date exists between these two dates but I need to adapt the query to include bookings where the date starts before '2018-06-01' but includes the daterange shown in the query above. 这将返回开始日期介于这两个日期之间的所有预订,但我需要对查询进行调整,以包括日期开始于“ 2018-06-01”之前但包含上面查询中显示的日期范围的预订。 I understand the DATEDIFF function but I am not sure how/whether I can use that to return a date that, for example starts at '2018-05-23' and finishes '2018-06-02' (within the date range above).
我了解DATEDIFF函数,但不确定如何/是否可以使用它返回一个日期,例如,从“ 2018-05-23”开始并完成“ 2018-06-02”(在上述日期范围内) 。
I think you want this logic: 我认为您需要以下逻辑:
SELECT b.*
FROM bookings b
WHERE b.datefrom <= '2018-06-07' AND
b.datefrom >= '2018-06-01';
This gives you any bookings that overlap with that period. 这将为您提供与该期间重叠的所有预订。
Following logic checks for overlapping date ranges: 以下逻辑检查日期范围是否重叠:
where start1 <= end2 and end2 >= start1
eg to find matching rows between '2018-06-01' and '2018-06-07' 例如在“ 2018-06-01”和“ 2018-06-07”之间找到匹配的行
WHERE datefrom <= '2018-06-07'
AND dateto >= '2018-06-01'
Depending on your logic you might need to switch >=
to >
根据您的逻辑,您可能需要将
>=
切换到>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.