【问题标题】:Structuring MySQL query efficiently有效地构建 MySQL 查询
【发布时间】: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


【解决方案1】:

我认为您想要在where 子句中的逻辑是:

checkin <= '$end' AND checkout >= '$start' and room = '$row1[room]'

在结束日期之前结账和在开始日期之后结账的两个日期之间有一个房间被占用。

编辑:

你的子句是:

checkin <= '$start' AND checkout >= '$end'

这与我的解决方案不同。

【讨论】:

  • 嗨,戈登。我想我的第二个查询(q2)中已经有了这个子句。问题是,如果有 20 个房间,那么这意味着需要运行 140 个查询来显示信息。如果可能的话,这就是我试图减少/提高效率的东西?谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 2010-11-06
  • 1970-01-01
相关资源
最近更新 更多