计算两个公寓空置时的时间 - mysql

时间:2014-01-15 16:41:57

标签: php mysql

我有2张桌子可以报告2个假期公寓的入住情况。

列是 id,arrivalweek,departureweek。简单的SMALLINT

我已经有一个系统,我可以在开始周和结束周指定一年中的一个时段,并查看该时段内单个公寓被占用的周数。这很好,如下所示,例如,看看公寓1在第5周和第22周之间占用了多少周......

$begin=5; // start of analysis period
$end=22;  // end of analysis period

 // ###############################################################################
// Apartment 1
// ##################################################################################
$totalperiod=0;$arrivalweek=0;$departureweek=0;$period=0;
foreach($db->query('SELECT   id, arrivalweek, departureweek FROM apartment1  WHERE departureweek > '.$begin.' AND arrivalweek < '.$end.'  ORDER BY id ASC') as $record)
{
$arrivalweek=$record['arrivalweek'];  
$departureweek=$record['departureweek']; 
if ($arrivalweek<$begin) {$arrivalweek=$begin;} // we might already be in occupancy.
if($departureweek>$end){$departureweek=$end;}   // we might not have vacated yet.
$period=$departureweek-$arrivalweek; // period for this sector
$totalperiod=$totalperiod+$period;  // add all sectors to get total period
}
echo "Time range from ".$begin." to ".$end.", for apartment 1<br>";
echo $totalperiod." = total weeks occupied for apartment 1 in that period<br>";
// ##################################################################################
// End of individual apartment occupancy code
// ##################################################################################

现在,我希望能够知道那个时期多少个星期两个公寓都没人住,并且很难找到解决方案。在指定的时间段内,公寓1未被占用且公寓2未被占用的总周数。

任何线索都非常欢迎!

由于

1 个答案:

答案 0 :(得分:0)

未测试(没有测试数据),但可能是这样的: -

SELECT COUNT(*)
FROM
(
    SELECT Tens.a * 10 + Units.a AS weekNumber
    FROM
    (SELECT 0 AS a UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Tens,
    (SELECT 0 AS a UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Units
    HAVING weekNumber BETWEEN $begin AND $end
) allWeeks
LEFT OUTER JOIN apartment1 ON allWeeks.weekNumber BETWEEN apartment1.arrivalweek AND  apartment1.departureweek
LEFT OUTER JOIN apartment2 ON allWeeks.weekNumber BETWEEN apartment2.arrivalweek AND  apartment2.departureweek
WHERE apartment1.id IS NULL
AND apartment2.id IS NULL

第一个子查询获取$ begin和$ end之间的周数列表。

这与每间公寓的预订表保持联系(注意,您可能应该为两个公寓设置一个表,其中一列定义了一行与哪个公寓相关)。然后,WHERE子句将忽略在连接上找到匹配项的任何行。