![](/img/trans.png)
[英]SQL query to select all rooms from a table which still have free capacity in date range
[英]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.