如何为查询提供更好的性能?

时间:2014-04-23 17:47:24

标签: sql sql-server tsql sqlperformance

我一直在阅读一些关于sql的“in statement”的文章。我学会了“IN”创造了一些糟糕的表现。我想在我的代码之上做出更好的表现。你能给我一些建议来实现这个目标吗?

select 
    v.Id,  
    v.MissingVehicleFlag,  
    v.Make,  
    v.OatsModelId,  
    v.Model,  
    v.PersonalisedName,  
    v.RegistrationPlate, 
    v.ImageUrl,  
    v.ImageCropStartingX,  
    v.ImageCropStartingY, 
    v.LastModified, 
    v.Account_Id, 
    v.Deleted
from RobbinsuatLatest.dbo.Vehicles v  
    where v.Id in(
        select v1.Id
        from RobbinsuatLatest.dbo.Vehicles v1 
        except
        select v2.Id from RobbinsuatLatest.dbo.VehiclesV2 v2
        )

2 个答案:

答案 0 :(得分:3)

SELECT 
    v.Id,  
    v.MissingVehicleFlag,  
    v.Make,  
    v.OatsModelId,  
    v.Model,  
    v.PersonalisedName,  
    v.RegistrationPlate, 
    v.ImageUrl,  
    v.ImageCropStartingX,  
    v.ImageCropStartingY, 
    v.LastModified, 
    v.Account_Id, 
    v.Deleted
FROM RobbinsuatLatest.dbo.Vehicles v  
LEFT JOIN RobbinsuatLatest.dbo.VehiclesV2 v2 on v.Id = v2.Id
WHERE v2.Id IS NULL

答案 1 :(得分:0)

使用NOT EXISTS

select 
    v.Id,  
    v.MissingVehicleFlag,  
    v.Make,  
    v.OatsModelId,  
    v.Model,  
    v.PersonalisedName,  
    v.RegistrationPlate, 
    v.ImageUrl,  
    v.ImageCropStartingX,  
    v.ImageCropStartingY, 
    v.LastModified, 
    v.Account_Id, 
    v.Deleted
from RobbinsuatLatest.dbo.Vehicles v  
    where NOT EXISTS (
        select v2.Id 
        from RobbinsuatLatest.dbo.VehiclesV2 v2
        WHERE v.Id = v2.Id
        )

确保IdRobbinsuatLatest.dbo.Vehicles

中的RobbinsuatLatest.dbo.VehiclesV2都有索引