如何测试特定时期是否存在重叠时期?

How to test if there are overlapping periods with a particular period?

在我的 table 中有两列日期类型和两列时间类型 :

这里是table的一些记录:

现在,在我的网络应用程序中,我想在其中插入一个新行 table :

提交表单时,我想计算输入的句点与数据库中已有的其他句点重叠的行数 table;按时期我的意思是一个(beginning_date,beginning_time)和一个(ending_date,ending_time)在一起,例如(2016-03-15,12:00:00)和 ( 2016-03-17 , 10:00:00 ).

我试过这个查询,但没有给出正确的结果:

select count(identifiant) from reservation_table where ( (date_debut <= '2016-03-14' and heure_debut <= '01:00:00') and (date_fin <= '2016-03-14' and heure_fin <= '03:00:00') and (date_fin > '2016-03-14' and heure_fin > '01:00:00') ) or 
( (date_debut >= '2016-03-14' and heure_debut >= '01:00:00') and (date_fin >= '2016-03-14' and heure_fin >= '03:00:00') and (date_debut < '2016-03-14' and heure_debut < '03:00:00') ) or 
( (date_debut >= '2016-03-14' and heure_debut >= '01:00:00') and (date_fin <= '2016-03-14' and heure_fin <= '03:00:00') ) or 
( (date_debut <= '2016-03-14' and heure_debut <= '01:00:00') and (date_fin >= '2016-03-14' and heure_fin >= '03:00:00') );

为了更好地理解重叠的时期,这里有一张图片:

因此在这张图片中,红色部分是从网络应用程序输入的时间段,黑色部分是已经在数据库中的时间段。那么如何获得与特定时期重叠的所有时期?

测试两个元素是否重叠的方法是检查一个是否在第二个结束之前开始,而第二个在第一个结束之前开始,如 tag wiki.
中所述 我对 MySql 没有太多经验,但确实发现 this methoddatetime:

创建一个 datetime
STR_TO_DATE(CONCAT(date, ' ', time), '%Y-%m-%d %H:%i:%s')

获得日期时间值后,您可以执行以下操作:

select count(identifiant) 
from reservation_table 
where @YourStartDatetime <= STR_TO_DATE(CONCAT(date_fin,' ', heure_fin), '%Y-%m-%d %H:%i:%s')
and @YourEndDateTime >=  STR_TO_DATE(CONCAT(date_debut ,' ', heure_debut), '%Y-%m-%d %H:%i:%s')

如果计数 returns 0,那么您没有记录与 @YourStartDatetime@YourEndDateTime

指定的时间段重叠