我正在构建一个PHP / MySQL查询,该查询列出了指定时间段内(例如一天)数据库中的所有预留。所有预订都有开始日期和结束日期。我需要列出它们,以便按升序显示它们1)start_date / end_date =指定时间段之间2)start_date& end_date可以在句点内,因此对于start_date应该有1个结果,对于end_date应该有另一个结果
SELECT *
FROM `reservations`
WHERE `start_date` BETWEEN '2017-01-04 00:00:00' AND '2017-01-04 23:59:59'
OR `end_date` BETWEEN '2017-01-04 00:00:00' AND '2017-01-04 23:59:00'
order by start_date, end_date
所以我需要帮助根据两列对结果进行排序,并且对于在指定时间段内同时包含start_date和end_date的行,重复结果。
更新
现在我已经得到了正确的结果,并且根据日期(start_date / end_date)按行升序排序。 但是如果我有人在同一天检查输入(即重复行),我当前的查询会背对背地列出行,尽管我希望根据退房时间排序第二行。 / p>
这是我到目前为止所拥有的:
select * from(SELECT id,start_date,end_date FROM
reservations
WHEREstart_date
BETWEEN'2017-01-03 00:00:00'EN'2017-01-03 23:59:59 '或end_date
BETWEEN'2017-01-03 00:00:00'和'2017-01-03 23:59:00'联合所有SELECT id,start_date,end_date FROMreservations
WHERE {{ 1}} BETWEEN'2017-01-03 00:00:00'和'2017-01-03 23:59:59'和start_date
BETWEEN'2017-01-03 00:00:00'AND' 2017-01-03 23:59:00')as tbl order by case WHEN start_date BETWEEN'2017-01-03 00:00:00'EN'2017-01-03 23:59:59'THEN start_date ELSE end_date END ASC
答案 0 :(得分:1)
你需要一个UNION ALL来复制行,因为OR条件会包含它们一次,你可以添加一个AND条件来复制那些完全落入那个日期范围的条件,如下所示:
select * from (
SELECT *
FROM `reservations`
WHERE `start_date` BETWEEN '2017-01-04 00:00:00' AND '2017-01-04 23:59:59'
OR `end_date` BETWEEN '2017-01-04 00:00:00' AND '2017-01-04 23:59:00'
union all
SELECT *
FROM `reservations`
WHERE `start_date` BETWEEN '2017-01-04 00:00:00' AND '2017-01-04 23:59:59'
AND `end_date` BETWEEN '2017-01-04 00:00:00' AND '2017-01-04 23:59:00'
) as tbl
order by start_date, end_date