[英]php mysql search for room availability need help for better sql query
my mysql database is: 我的mysql数据库是:
BOOKING_ID, FROM_DATE, TO_DATE,
R1,R2,R3,R4,R5,R6,R7,R8,R9,R10,R11,R12,R13,R14,R15,R16,R17
where R1=room1...R17=room17, if room1 booked, than R1 will set to 1. 其中R1 = room1 ... R17 = room17,如果预订了room1,则R1将设置为1。
below is my current working sql query,i never learn sql before, i need help for better sql query! 以下是我目前正在使用的sql查询,我以前从没学习过sql,我需要帮助以获取更好的sql查询!
for($room=1;$room<=$total_room;$room++)
{
$result = mysql_query("
SELECT COUNT(`BOOKING_ID`) AS num
FROM $search_for_db_table
WHERE ( (FROM_DATE <= $search_to_date AND TO_DATE >= $search_to_date )
OR (FROM_DATE <= $search_from_date AND TO_DATE >= $search_from_date)
OR (FROM_DATE >= $search_from_date AND TO_DATE <= $search_to_date )
)
AND R$room=1
") or die(mysql_error());
$row = mysql_fetch_assoc($result);
$numUsers[$room] = $row['num'];
}
//$numUsers[$room]=="0" means room available for booking...
Please learn more about designing your database. 请了解有关设计数据库的更多信息。 Instead of using a column for every room just use multiple tables to get the information, that way it is much more organized. 不用为每个房间都使用一列,而是使用多个表来获取信息,这样可以使信息更加井井有条。
So make a table called 'rooms' in that table you make let's say 15 rows. 因此,在该表中创建一个名为“ rooms”的表,假设有15行。 With a column 'room_number' for the room number and a column 'available' with your 1 or 0. A simple SQL statement then show what rooms are available. 在“ room_number”列中输入房间号,在“ available”列中输入1或0。然后,一个简单的SQL语句显示可用的房间。
Then you can use: 然后,您可以使用:
SELECT 'room_number' FROM rooms WHERE available = '0'
Yet, if you don't like to modify this "ugly" data model you can go with 1 query and not with 17 queries. 但是,如果您不想修改此“丑陋”的数据模型,则可以使用1个查询,而不使用17个查询。 Simply use SUM( for all 17 fields. So the SELECT clause would be: 只需对所有17个字段使用SUM(。那么SELECT子句将为:
SELECT SUM(R1) AS sr1, SUM(R2) AS sr2, ...., SUM(R17) as sr17
FROM
WHERE [only with the date restictions]
Then if the respective column of the result set is 0 then it is available, otherwise it is occupied. 然后,如果结果集的相应列为0,则该列可用,否则将被占用。
But again, this is an "ugly" solution for the wrongly designed data model. 但是同样,对于错误设计的数据模型,这是一个“丑陋”的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.