簡體   English   中英

SQL查詢以選擇沒有與輸入日期關聯的預訂的房間

[英]SQL Query to select rooms that do not have a booking associated with the input date

我有一個與春季預訂房間應用程序相關的MySQL數據庫,其中包含“ rooms”表,如下所示:

 id | building | capacity | room_no |
+----+----------+----------+---------+
|  1 | Queens   |        6 | 0.11a   |
|  2 | Queens   |        6 | 0.18a   |
|  3 | Queens   |        6 | 0.18b   |
|  4 | Queens   |        6 | 0.18c   |
|  5 | Queens   |        6 | 0.18d   |
|  6 | Queens   |        6 | 0.18e   |
|  7 | Queens   |        6 | 1.5A    |
|  8 | Queens   |        6 | 1.5B    |
|  9 | Queens   |        6 | 1.8A    |
| 10 | Queens   |        6 | 1.8B    |
| 11 | Queens   |        6 | 1.8C    |
| 12 | 100      |      100 | 100 

預訂表如下所示:

| id | date_time           | length | room_id | user_id | creation_date |
+----+---------------------+--------+---------+---------+---------------+
|  1 | 2012-06-18 10:34:09 |      1 |       1 |       1 | NULL          |
|  9 | 1111-11-11 11:11:00 |      1 |       2 |       8 | NULL          |
| 13 | 2001-01-01 01:01:00 |      3 |      12 |      11 | NULL          |
| 14 | 0001-01-01 01:01:00 |      1 |      12 |      11 | NULL          |
+----+---------------------+--------+---------+---------+---------------+

我試圖在春季編寫一個SQL查詢,給定日期和長度輸入,該查詢返回在該輸入時間沒有預訂的房間的列表。

到目前為止,我的嘗試是非常錯誤的:

"
select r 
  from room r 
  join booking b 
    on r.id = b.id 
 where b.date_time = :#{#booking.getDateTime()} 
   and b.length = :#{#booking.getLength()}
"

任何幫助將是巨大的!

謝謝

在SQL中,您可以將其寫為not exists查詢:

select r.*
from rooms r
where not exists (select 1
                  from bookings b
                  where b.room_id = r.room_id and
                        @input_date_time < date_add(b.date_time, interval length ???) and
                        date_add(@input_date_time, interval @input_length ???) > b.date_time
                 );

??? 適用於您使用的length單位(通常稱為duration )。

您應該在Repository界面中編寫如下代碼:

    @Repository    
    public interface RoomRepository extends CRUDRepository<Room, Long>{
            private final String QUERY_STRING = "
            select r 
              from room r 
              join booking b 
                on r.id = b.id 
             where b.date_time = :date
               and b.length = :len
            ";

            @Query(QUERY_STRING)
            Room getRooms(LocalDateTime date, Integer len);
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM