如何编写合并两个记录的函数

时间:2016-09-01 09:25:21

标签: php mysql sql database

我有数据库结构

--car_id 
--from_date_time
--to_date_time
--is_booked

我想这样做:

If any two records having is_booked == 'N" exists in database, having overlapping from_date_time and to_date_time, 
then these records will be merged into a single record.

示例:

If i have records in database like:
Record 1:
from_date_time = '2016-08-01 04:00:00';
to_date_time = '2016-08-01 06:00:00';

Record 2:
from_date_time = '2016-08-01 03:00:00';
to_date_time = '2016-08-01 05:00:00';

Then,above two records will get merged to create following:
from_date_time = '2016-08-01 03:00:00';
to_date_time = '2016-08-01 06:00:00';

我试过以下:

i) Check if the looped_from_date_time is in any database record with from_date_time >= looped_from_date_time  and to_date_time <= looped_from_date_time  and is_booked = "N" and car_id = $car_id.

   iii) Check if the looped_to_date_time is in any database record with from_date_time >= looped_to_date_time and to_date_time <= looped_to_date_time and is_booked = "N" and car_id = $car_id.

但它不起作用

1 个答案:

答案 0 :(得分:0)

'Period1'与'Period2'重叠

if

NOT ( end_of_period1 < beginning_of_period2 OR 
beginning_of_period1 > end_of_period2). 

这是涵盖所有可能情况的唯一方法。

在你的情况下,我认为第一个条件(I)总是错误的: 如果'from_date_time'在所有记录中始终低于'to_date_time',则您不能拥有"from_date_time >= looped_from_date_time and to_date_time <= looped_from_date_time"