1

所以我有这段代码。它从“rom”表中检索房间列表,然后应该对照“booket”中的相同房间进行检查。我怎样才能在设定的时间内打印出不在 booket 中的房间。

“Rom”-数据库如下所示:

romnavn   | romtype (not relevant here)

ex: 81-77 | 2

“小册子”看起来像:

romnavn   | bruker      | dato       | fra | til

ex: 81-77 | foo@bar.net | 03.04.2013 | 16  | 18

(这意味着房间将在 16:00:00 至 18:00:00 之间预订)

如果房间出现在两个查询中,则应该忽略它。

我的猜测是两个while循环,“ $notFreeA”在第一个里面,但我没有得到我想要的结果。

我相当确定数据库和查询都是,嗯..,不好,但任何帮助将不胜感激:)

require "sql/sqlConnect.php";
require "functions/functions.php";
date_default_timezone_set('Europe/Oslo');
$time = date('H:i:s');
$date = date('d.m.Y');
$nearestHour = roundToNearestHour($time);

$allRooms = "SELECT * FROM rom";
$notFree = "SELECT * FROM booket WHERE dato='$date' AND fra<='$nearestHour';";

$allRoomA = mysql_query($allRooms);
$notFreeA = mysql_query($notFree);

向上/向下舍入到最近房间的函数如下所示:

function roundToNearestHour($time) {
$part = explode(":", $time);

if(count($part) != 3)
  return 0;

if($part[2] > 30)
  $parts[1]++;

if($part[1] > 30)
  $part[0]++;

return $part[0];
}
4

2 回答 2

1

Try doing this with one query:

select *
from room r
where r.romnavn not in (select roomnavn booket WHERE dato='$date' AND fra<='$nearestHour')
于 2013-04-03T14:58:12.847 回答
1

You only need one query to do this. Any one of these three will produce the results you desire:

SELECT * FROM rom WHERE NOT EXISTS 
  (SELECT * FROM booket WHERE dato='$date' AND fra<='$nearestHour'
   AND rom.romnavn = booklet.romnavn)

SELECT rom.* FROM rom LEFT OUTER JOIN booket USING romnavn
   WHERE dato='$date' AND fra<='$nearestHour' AND booket.romnavn IS NULL

SELECT * FROM rom WHERE romnavn NOT IN
   (SELECT romnavn FROM booket WHERE dato='$date' AND fra<='$nearestHour')

That said, this table design is very poor. You don't appear to be using native datetime types, and your primary keys are poorly named and should be something easier to index (like integer ids).

If there's only one change you can make, you should at least ensure that the dato column is actually a DATE type and not a varchar. As it is, any date-based sorting or filtering will be extremely difficult to perform with SQL.

于 2013-04-03T14:59:23.043 回答