根据我的条件,查询没有给出正确的结果

时间:2013-09-19 12:00:29

标签: sql

我的表名在下面给出

1)tblCarName
2)tblVehicle
3)tblModel
4)tblVehicleAvailability

以上三张表中我有取车结果,车辆没有预订,具体型号,然后是特定日期车辆可用或不可用的另一个状态车辆可用状况。
但我得到的结果是哪辆车不可用。 (表示那些在tblVehicleAvailability表中的车)但我想要那些不在tblVehicleAvailability表中的车)

我的查询

select 
    A.id,
    C.vsCarName+' ('+ A.EngineNum+' )' as vsCarName   
from tblCarName C 
join tblVehicle A on C.id = A.CarId
inner join tblModel B on A.ModelId = B.id 

--join tblVehicleAvailability VA on  VA.CarId = A.id

WHERE A.id not in 
(
    SELECT 
        VehicleId 
    FROM 
        tblBooking
    WHERE 
        A.ActiveInactive = 1
    AND 
        Convert(datetime,'2013-09-19 00:00:00.000') --start date
            BETWEEN FromDateWithStartTime AND ToDateWithEndTime
    OR 
        Convert(datetime,'2013-09-20 00:00:00.000')  --endDate
            BETWEEN FromDateWithStartTime AND ToDateWithEndTime
    OR 
        FromDateWithStartTime 
            BETWEEN Convert(datetime,'2013-09-19 00:00:00.000') --startdate  
          AND Convert(datetime,'2013-09-20 00:00:00.000')  --enddate  
    OR 
        ToDateWithEndTime 
            BETWEEN Convert(datetime,'2013-09-19 00:00:00.000')--start date  
            AND Convert(datetime,'2013-09-20 00:00:00.000')--enddate
) 
AND  
    A.ModelId='3' 
AND   
    Convert(datetime,'2013-09-19 00:00:00.000')  --start date  
    BETWEEN VA.leaveDate AND VA.leaveToDate  
OR 
    Convert(datetime,'2013-09-20 00:00:00.000') --endDate  
    BETWEEN VA.leaveDate AND VA.leaveToDate  
OR 
    VA.leaveDate 
    BETWEEN Convert(datetime,'2013-09-19 00:00:00.000') --startdate  
    AND Convert(datetime,'2013-09-20 00:00:00.000')  --enddate  
OR 
    VA.leaveToDate
    BETWEEN Convert(datetime,'2013-09-19 00:00:00.000') --start date
    AND Convert(datetime,'2013-09-20 00:00:00.000')

2 个答案:

答案 0 :(得分:1)

请改为尝试:

select A.id ,C.vsCarName+' ('+ A.EngineNum+' )' as vsCarName   
from tblCarName C 
inner join tblVehicle A on C.id=A.CarId
inner join tblModel B on A.ModelId=B.id 
where not exists (
    select null from tblBooking
    where A.id = VehicleId and
    A.ActiveInactive = 1 and 
    '20130919' <= ToDateWithEndTime 
    and '20130920' >= FromDateWithStartTime
    ) 
and  A.ModelId='3' AND
'20130919' <= VA.leaveToDate  
and '20130920' >= VA.leaveDate

答案 1 :(得分:0)

通常当我看到“OR”语句时,我开始添加(),这样我得到了我想要的东西。

编辑: 但您可能还想查看使用LEFT JOIN tblVehicleAvailability

和另外的where子句:

WHID CarID为NULL

祝你好运, 亨利克