2016-03-18 28 views
0

在我的桌子有日期类型的两列的类型时两列:如何测试特定期间是否有重叠期?

enter image description here

下面是表的一些记录:

enter image description here

现在,在我的网页应用程序我想在该表格中插入新行:

enter image description here

提交表单时,我想计算输入期间与已存在于数据库表中的其他行重叠的行数;期间我的意思是(begin_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')); 

要对此处重叠期更好地理解为图像:

enter image description here

所以在这种图像红色时期是从网络应用程序输入的时期,黑色时期是那些已经在数据库中的时期。那么如何让所有的时期重叠到一个特定的时期?

+0

你的代码将是简单了很多,如果你只是有一个“日期时间”列。此代码将为您创建列: UPDATE table SET datetime_field = CONCAT(date_field,“”,time_field); 此外,你似乎有双引号“之前每个分号,这些应该是两个单引号''?对不起,如果这是一个MySQL的事情,我不太熟悉它 –

+0

好吧,双引号是因为我构建了一个PHP变量的查询 – pheromix

+0

那么如何测试使用'datetime'列的时间段重叠? – pheromix

回答

1

测试如果两个元素重叠是检查是否一个第二结束前开始,而第一端前一秒开始,如标签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') 

如果计数返回0,那么你有没有记录重叠的指定的时间内通过@YourStartDatetime@YourEndDateTime

相关问题