我正在尝试创建一个查询,该查询根据用户输入的from和to日期从我的数据库返回可用的车辆。
这是我预订表中的日期。
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-13
放到27-JAN-13
,上表中的这两辆车将从结果中省略,因为它们已被预订。但是,如果我将23-JAN-13
放入24-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);
因为我正在使用&lt; =和&gt; = equals部分将导致它省略它们,因为它们是相同的,或者我错了?
答案 0 :(得分: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);
答案 1 :(得分: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')))