创建SQL查询

时间:2017-05-05 11:33:12

标签: mysql sql

我有查询问题.. 基本上在我的酒店预订网站上有预订 预订有入住日期退房日期

我需要一个SQL查询

  

检测新的签入签出日期是否在任何范围内   表格中签入签出日期

我当前的查询不起作用,因为它无法检测新输入的签入日期何时在数据库签入日期之前开始,并且新输入的签出日期在数据库中的签出日期之后结束。

感谢您的帮助!

当前代码(我不确定你是否想在纯sql中使用它......

// Gets the Checkin and checkout dates from the session variable
        $FirstDate = $request->session()->get('checkin');
        $SecDate = $request->session()->get('checkout');

        // Tries to match the checkin and checkout dates with other reservations of the same Hotel room
        foreach ($Rooms as $Room) {
            $Id =  $Room->id;

            $RoomsBooked = Reservation::where('room_id','=', $Id)
            ->where('CheckIn','>=',$FirstDate)
            ->where('CheckOut','<=',$SecDate)

                ->orWhere(function($query) use ($FirstDate,$Id)
                    {
                      $query->where('room_id','=', $Id)
                            ->where('CheckIn','<=',$FirstDate)

                            ->where('CheckOut','>=',$FirstDate);
                          })

                            ->orWhere(function($query2) use ($FirstDate,$SecDate,$Id)
                            {
                              $query2->where('room_id','=', $Id)
                                    ->where('CheckIn','>=',$FirstDate)

                                    ->where('CheckIn','<=',$SecDate);
                                  })->count();


                  // Works out How many rooms are available
                  $Roomsavailable = $Room->TotalRooms;
                  $Roomsleft =  $Roomsavailable - $RoomsBooked;
                  $Room->spaceleft = $Roomsleft;
            }

1 个答案:

答案 0 :(得分:1)

检查两个日期范围是否重叠的基本逻辑是:

where start1 < end2 and end1 > start2

如果您希望相同的日期计为重叠,请将<替换为<=等。

因此,在您的代码中,我认为您只需要一个单个位置来检查:

        ->where('CheckIn','<=',$SecondDate)
        ->where('CheckOut','>=',$FirstDate);