0

我正在尝试创建一个查询,该查询根据用户输入的起始日期和结束日期从我的数据库返回可用车辆。

这是目前我预订表中的日期。

Booking Table
booking_id     customer_id    reg_number    date_from    date_to    status
1              2              RH34 TJT      23-JAN-13    24-JAN-13  1
2              3              RJ54 FKF      26-JAN-13    26-JAN-13  1     

下面是我的查询,如果我输入的日期不等于预订表中已经存在的日期,它会起作用。例如,如果我将22-JAN-1327-JAN-13表中的那两辆车放在结果中,因为它们已被预订。但是,如果我输入23-JAN-1324-JAN-13这天预订的车也会在不应该的时候被退回,因为它已经预订了。

SELECT   *
FROM vehicles
INNER JOIN car_model ON vehicles.model_code = car_model.model_code
INNER JOIN manufacture ON car_model.manufacture_code = manufacture.manufacture_code
LEFT OUTER JOIN booking ON vehicles.reg_number = booking.reg_number
WHERE ((booking.date_from <= '23-JAN-13' OR booking.date_from >= '24-JAN-13')
        AND (booking.date_to <= '23-JAN-13' OR booking.date_to >= '24-JAN-13')
        AND booking.booking_status = 1);

因为我使用 <= 和 >= 等于部分会导致它在它们相等时省略它们,还是我错了?

4

2 回答 2

0

试试这个

SELECT   *
FROM vehicles
INNER JOIN car_model ON vehicles.model_code = car_model.model_code
INNER JOIN manufacture ON car_model.manufacture_code = manufacture.manufacture_code
LEFT OUTER JOIN booking ON vehicles.reg_number = booking.reg_number
WHERE ((booking.date_from < '23-JAN-13' OR booking.date_from > '24-JAN-13')
        AND (booking.date_to < '23-JAN-13' OR booking.date_to > '24-JAN-13')
        AND booking.booking_status = 1);
于 2013-01-24T14:29:28.040 回答
0

如果您正在寻找在给定日期未预订的车辆,您应该寻找使用NOT EXISTS而不是加入VEHICLES表格:

SELECT *
FROM   vehicles v
WHERE  NOT EXISTS (SELECT NULL
                   FROM   booking b
                   WHERE  b.reg_number = v.reg_number
                   AND    b.booking_status = 1
                   AND    ((b.date_to > to_date(:start_date,  'DD/MM/YYYY') AND b.date_from <= to_date(:start_date, 'DD/MM/YYYY')) OR 
                           (b.date_from <= to_date(:end_date, 'DD/MM/YYYY') AND b.date_to > to_date(:end_date, 'DD/MM/YYYY')) OR
                           (b.date_from <= to_date(:start_date, 'DD/MM/YYYY') AND b.date_to >= to_date(:end_date, 'DD/MM/YYYY')) OR
                           (b.date_from >= to_date(:start_date, 'DD/MM/YYYY') AND b.date_to <= to_date(:end_date, 'DD/MM/YYYY')))
于 2013-01-24T14:43:32.460 回答