MS SQL合并两个查询以获得一个结果

时间:2015-05-21 13:05:22

标签: sql sql-server tsql join

我正在实施车辆管理系统。我有两个不同的查询,一个用于获取代理商的所有车辆,另一个用于获取司机。每辆车都有一个司机一次分配给它。 现在我想合并这两个查询以返回车辆详细信息以及分配给车辆的驱动程序的详细信息。

获取驱动程序及其名称的第一个查询:

SELECT UserInfo.Name
FROM DriverInfo INNER JOIN UserInfo ON DriverInfo.Email = UserInfo.Email 
    INNER JOIN Agency ON UserInfo.AgencyID = Agency.AgencyID 
WHERE (UserInfo.AgencyID = 1) 
ORDER BY DriverInfo.DriverId DESC

获取车辆详细信息的第二个查询:

SELECT Vehicle.VehicleRegNum AS [Registration Number], 
    Vehicle.EngineNum AS [Engine Number], 
    Vehicle.FileRef AS [File Refrence], 
    Type.Name AS Type, 
    Make.Name AS Make ,
    Vehicle.DriverID AS DriverID
FROM Vehicle INNER JOIN Type ON Vehicle.Type = Type.TypeId 
    INNER JOIN Make ON Vehicle.Make = Make.MakeId 
WHERE (Vehicle.Approve = 1) 
    AND (Vehicle.AgencyId = 1) 
    AND (Vehicle.Maintained = 1) 
ORDER BY Vehicle.VId DESC

在此查询中,我收到了DriverID 并在DriverInfo中:

DriverId, LicenseType, AppointmentDate, LicenseExpiryDate, ContractExpiryDate, Email

2 个答案:

答案 0 :(得分:1)

只需添加联接中的其他表格。

SELECT Vehicle.VehicleRegNum AS [Registration Number], 
Vehicle.EngineNum AS [Engine Number], 
Vehicle.FileRef AS [File Refrence], 
Type.Name AS Type, 
Make.Name AS Make,
DriverInfo.DriverId,
DriverInfo.LicenseType,
DriverInfo.AppointmentDate,
DriverInfo.LicenseExpiryDate,
DriverInfo.ContractExpiryDate,
DriverInfo.Email
FROM Vehicle 
INNER JOIN Type 
    ON Vehicle.Type = Type.TypeId 
INNER JOIN Make 
    ON Vehicle.Make = Make.MakeId 
INNER JOIN DriverInfo 
    ON Vehicle.DriverID = DriverInfo.DriverId
INNER JOIN UserInfo 
    ON DriverInfo.Email = UserInfo.Email 
INNER JOIN Agency 
    ON UserInfo.AgencyID = Agency.AgencyID 
    AND Vehicle.AgencyID = Agency.AgencyID
WHERE (Vehicle.Approve = 1) 
AND (Vehicle.AgencyId = 1) 
AND (Vehicle.Maintained = 1) 
ORDER BY Vehicle.VId DESC

答案 1 :(得分:1)

我相信以下内容可行,具体取决于您的要求,您可能需要更改JOIN类型的DriverInfo

SELECT Vehicle.VehicleRegNum AS [Registration Number]
    ,Vehicle.EngineNum AS [Engine Number]
    ,Vehicle.FileRef AS [File Refrence]
    ,Type.NAME AS Type
    ,Make.NAME AS Make
    ,UserInfo.NAME AS Driver
FROM Vehicle
INNER JOIN Type ON Vehicle.Type = Type.TypeId
INNER JOIN Make ON Vehicle.Make = Make.MakeId
LEFT JOIN DriverInfo ON DriverInfo.DriverID = Vehicle.DriverID
LEFT JOIN UserInfo ON DriverInfo.Email = UserInfo.Email
    AND (UserInfo.AgencyID = 1)
--Agency is never used, so don't join?
--LEFT JOIN Agency ON UserInfo.AgencyID = Agency.AgencyID
WHERE (Vehicle.Approve = 1)
    AND (Vehicle.AgencyId = 1)
    AND (Vehicle.Maintained = 1)
ORDER BY Vehicle.VId DESC