【发布时间】:2017-10-07 22:40:33
【问题描述】:
我正在寻求有关如何最好地构建 MySQL 查询并显示结果的帮助。我正在尝试在 PHP 页面上创建一个表格,该表格顶部有 7 个日期,侧面有房间号。在表格中,如果一个人在给定日期在一个房间里,那么他们的名字就会出现。我有以下表格:
表格: 房间
字段: id、房间
表格:预订
字段:id、姓名、房间、入住、结账
我目前拥有的代码是:
<? $start = date('Y-m-d');
$end = date('Y-m-d', strtotime($start." + 6 day")); ?>
<table class="table1">
<thead>
<tr>
<th></th>
<th scope="col"><?= date('d-m', strtotime($start)); ?></th>
<th scope="col"><?= date('d-m', strtotime($start." + 1 day")); ?></th>
<th scope="col"><?= date('d-m', strtotime($start." + 2 day")); ?></th>
<th scope="col"><?= date('d-m', strtotime($start." + 3 day")); ?></th>
<th scope="col"><?= date('d-m', strtotime($start." + 4 day")); ?></th>
<th scope="col"><?= date('d-m', strtotime($start." + 5 day")); ?></th>
<th scope="col"><?= date('d-m', strtotime($start." + 6 day")); ?></th>
</tr>
</thead>
<tbody>
<? $q1 = mysqli_query($con,"SELECT * FROM rooms GROUP BY room");
while($row1 = mysqli_fetch_assoc($q1)){ ?>
<tr>
<th><?= $row1['room']; ?></th>
<? $i = 0;
while ($i <= 6) { ?>
<td>
<? $q2 = mysqli_query($con,"SELECT * FROM bookings WHERE ((checkin BETWEEN '$start' and '$end') or (checkout BETWEEN '$start' and '$end') or (checkin <= '$start' AND checkout >= '$end')) and room = '$row1[room]'");
while($row2 = mysqli_fetch_assoc($q2)){
if ($row2['checkout'] > date('Y-m-d', strtotime($start." + ".$i." day")) and $row2['checkin'] <= date('Y-m-d', strtotime($start." + ".$i." day"))) {
echo $row2['name'];
}
} ?>
</td>
<? ++$i;
} ?>
</tr>
<? } ?>
</tbody>
</table>
这段代码目前产生了我需要的结果,但是我担心它效率低下,因为它运行大量的循环和查询来获取数据。
谁能建议一种更好的格式化查询/结果的方法?
【问题讨论】:
-
从了解 SQL JOINS 开始
-
可能想要一个 google 用于 mysql pivot 查询
-
记住,时间是线性的,所以你只对 x_start 为 y_start 的时间感兴趣!
标签: php mysql performance html-table