im 创建一个小型租车系统,我想要一个存储过程,它接受一个日期并检查哪些汽车可用。我已经有了比较工作,但如果一辆汽车有多个合同,并且其中一个合同不是输入的日期,而是另一个合同说汽车可用。以下是我到目前为止的程序
delimiter //
create procedure allAvailableVehicles(req varchar(15))
BEGIN
select distinct vehicles.vehicleID as "Vehicle ID", vehicles.Make as "Make", vehicles.Model as "Model" from vehicles
left outer join contracts
on vehicles.vehicleID=contracts.vehicleID
where cast(req as date) not between hiredFrom and hiredUntill
or contractID is unknown
order by vehicles.vehicleID;
end
//
delimiter ;
这是使用not exists
的好机会:
select v.*
from vehicles v
where not exists (select 1
from contracts c
where c.VehicleId = v.VehicleId and
cast(req as date) between hiredFrom and hiredUntil
);
注意:您不需要将req
转换为日期,因为它应该已经作为日期存储在数据库中(除非req
也有时间部分)。
编写存储过程的更好方法是:
delimiter //
create procedure allAvailableVehicles(p_req date)
begin
select v.*
from vehicles v
where not exists (select 1
from contracts c
where c.VehicleId = v.VehicleId and
p_req between hiredFrom and hiredUntil
);
end //
delimiter ;
对日期/时间使用内置类型。 此外,命名参数以将它们与列区分开来。