我目前正在为我的学校开发设备预订系统。
我的表格基本上是这样的:
tbl设备:
id name description 1 Camera Takes pictures 2 Projector Projects images 3 Stereo Plays music
tblEvents:
id equipmentID start end 1 2,3 1251312300 1251315900 //Should I use comma delimited entries for equipmentID? 2 1 1251312300 1251315900
Regarding my project, I have a couple of questions:
1) If multiple pieces of equipment are being reserved, (which will happen more times than not) should the "equipmentIDs" be comma delimited in the equipmentID field?
2) Currently, when a user makes a reservation, they first select their "requested times", then are presented with available items at that time. Here's what I am using for that query:
$start = //user's requested time
$start = //user's requested time
SELECT equipmentID FROM tblEvents
WHERE ($start >= start && $start <= end)
OR ($end >= start && $end <= end)
OR ($start <= start && $end >= end
while($row = mysql_fetch_array($data)) {
echo $row['equipmentID']; //Would echo something like:
echo "<br>"; // 2,3
// 1
}
我的问题是:
我如何获取上述查询的“结果”然后重新查询“tblequipment”表,但排除上面“结果”中的项目(因为它们不可用)。请记住,我上面的查询可能会返回多行。
任何帮助都将非常有用,谢谢!
最佳答案
关于#1:不!不不不不不不!如果您有多件设备被预订,那么您应该在预订表中有多个行(这里看起来像 tblEvents
)。为避免重复 tblEvents
中的 other 字段,您通常会创建第三个表,也许是 tblEventEquipment
,它只是列出了哪些设备属于哪些事件.
如果您出于输出目的需要一个逗号分隔的列表(这似乎不太可能),您始终可以使用 GROUP_CONCAT()
生成一个列表,但在表格中您需要一行每件保留的设备。否则,SQL 无法有效(或高效)确定在特定时间保留了哪些设备。
关于#2,你想要这样的查询:
SELECT *
FROM tblEquipment
WHERE NOT EXISTS (
SELECT 1
FROM tblEvents
WHERE tblEvents.equipmentID = tblEquipment.equipmentID
AND $end >= start AND $start <= end
)
这会选择没有预订的设备。请注意,我通过仅进行两次比较来简化您确定设备是否已保留的逻辑。
最后,一个不相关的说明:我强烈建议不要将时间戳作为整数存储在数据库表中。使用 MySQL 的内置 DATETIME
类型。如果需要与时间戳相互转换,可以使用 UNIX_TIMESTAMP()
和 FROM_UNIXTIME()
函数。
关于PHP/MySQL订房系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1302970/