【问题标题】:SQL Query to select rooms that do not have a booking associated with the input date用于选择没有与输入日期关联的预订的房间的 SQL 查询
【发布时间】:2019-03-22 10:43:48
【问题描述】:

我有一个与房间预订春季应用程序相关的 MySQL 数据库,其中包含如下所示的“房间”表:

 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()}
"

任何帮助都会很棒!

谢谢

【问题讨论】:

  • 您是否尝试过编写查询?通常,问题在表现出一些努力时会在这里得到更多关注。
  • 什么单位是length?

标签: mysql sql spring


【解决方案1】:

在 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)的任何单位。

【讨论】:

    【解决方案2】:

    你应该在你的 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);
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多