如何在JPQL中编写此SQL查询

时间:2013-02-02 19:46:54

标签: mysql sql jpa jpql

我希望将以下SQL转换为JPQL:

SELECT  *
FROM    rooms
WHERE   NOT EXISTS
(        
    SELECT  *
    FROM    booking, booking_has_rooms
    WHERE   rooms.number=booking_has_rooms.rooms_number AND 
            booking.booking_id=booking_has_rooms.booking_booking_id AND 
            :date BETWEEN booking.checkin AND booking.checkout
);

到目前为止,我有这个:

SELECT rooms 
FROM Rooms rooms 
WHERE NOT EXISTS 
(
    SELECT bk 
    FROM Booking b 
    JOIN  b.roomsCollection bk 
    WHERE :date BETWEEN b.checkin AND b.checkout
)

如果指定日期没有预订,则会正确返回所有房间。 但是,如果在指定日期进行任何预订 - 它根本不会返回任何房间。

1 个答案:

答案 0 :(得分:1)

您在内部查询中缺少一个子句:

SELECT rooms 
FROM Rooms rooms 
WHERE NOT EXISTS 
(
    SELECT bk 
    FROM Booking b 
    JOIN  b.roomsCollection bk 
    WHERE :date BETWEEN b.checkin AND b.checkout
    and bk.id = rooms.id
)

如果您将Rooms重命名为Room,您的代码会更加清晰。每个实例都是一个单独的房间,所以它应该使用单数形式。