I have a MySQL database related to a room booking spring application with a table of 'rooms' that looks like this:
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
and a table of bookings that looks like this:
| 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 |
+----+---------------------+--------+---------+---------+---------------+
I am trying to write an SQL query in spring that, given a date and length input, returns a list of rooms that do not have a booking at that input time.
My attempts are pretty wrong so far:
"
select r
from room r
join booking b
on r.id = b.id
where b.date_time = :#{#booking.getDateTime()}
and b.length = :#{#booking.getLength()}
"
Any help would be great!
Thanks
In SQL, you could write this as a not exists
query:
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
);
The ???
is for whatever units you are using for length
(which would normally be called duration
).
You should write something like this in your Repository interface :
@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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.