我必须检查mysql中的某些时间与特定时间计划的重叠 像:
time_plan1 = 2011-06-30, startTime = 09:00:00, finishTime = 10:00:00
time_plan2 = 2011-06-30, startTime = 12:30:00, finishTime = 13:30:00
time_plan3 = 2011-06-30, startTime = 14:00:00, finishTime = 15:30:00
time_plan4 = 2011-06-30, startTime = 17:00:00, finishTime = 18:00:00
和时间
time1 = 2011-06-30, startTime = 08:30:00, finishTime = 10:00:00
time2 = 2011-06-30, startTime = 12:30:00, finishTime = 13:30:00
time3 = 2011-06-30, startTime = 14:00:00, finishTime = 15:00:00
time4 = 2011-06-30, startTime = 16:30:00, finishTime = 19:00:00
所以我必须找到每个时间计划和时间的时间计划和时间之间的重叠但我不能指定哪个时间属于哪个时间计划
对于结果我需要具有属于时间计划的时间总和 在这种情况下 : 时间1:1h 时间2:1h 时间3:1h 时间4:1h 总计2011-06-30:4h
答案 0 :(得分:2)
WHERE time1.startTime > time_plan1.startTime and time1.finishTime < time_plan1.finishTime
这几乎是正确的,但您只能获得时间比时间计划晚开始的时间,并且时间早于时间计划结束。
要获得重叠,
WHERE time1.startTime < time_plan1.startTime or time1.finishTime > time_plan1.finishTime
这样做是抓住这3个重叠的场景
棘手的部分是得到重叠的总和,我认为你需要PHP
,因为sql
处理它会很复杂。
假设您已收到带有时间和时间计划的startTime和finishTime字段的记录。
$sum = 0; // seconds
foreach ($records as $record) {
$overlap_start = max($record->time_startTime, $record->timeplan_startTime);
$overlap_finish = min($record->time_finishTime, $record->timeplan_finishTime);
$sum += strtotime($overlap_finish) - strtotime($overlap_start);
}
答案 1 :(得分:1)
foreach($plan as $wpk=>$pla){
foreach($work as $wtk=>$wor){
if($wor['start']<$pla['end'] and $wor['end']>$pla['start']){
$overlap_start = max($wor['start'],$pla['start']);
$overlap_finis = min($wor['end'], $pla['end']);
$sum += $overlap_finis - $overlap_start;
if($overlap_start>$wor['start'])
$work[] = array('start'=>$wor['start'],'end'=>$overlap_start);
if($wor['end']>$overlap_finis)
$work[] = array('start'=>$overlap_finis,'end'=>$wor['end']);
unset($work["$wtk"]);
}
}