2015-05-21 133 views
0

我正在實施車輛管理系統。我有兩個不同的疑問,一個是提取一個機構的所有車輛,另一個是提取司機。每輛車都有一個分配給它的駕駛員。 現在我想合併這兩個查詢來返回車輛詳細信息以及分配給車輛的驅動程序的詳細信息。MS SQL合併兩個查詢以獲得一個結果

1查詢來獲取司機和他們的名字:

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 
+0

如何是這兩個相關?什麼是桌子結構?我沒有看到任何可用於將一個查詢與另一個查詢關聯的列。 – TTeeple

+0

@Tepleple看到更新的問題 –

+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 
+0

它的工作,但沒有返回正確的數據,然後我的第二個查詢返回36條記錄,但您的查詢返回21條記錄。 –

+0

就像@NickyvV說的,你可能需要改變連接以適合你的需求。我們不知道您有什麼類型的業務規則。 – TTeeple

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 
+0

爲什麼你的用戶where子句兩次? '關鍵字'WHERE'附近語法不正確。' –

+0

你說得對,我把它改成了'AND' – NickyvV

+1

UserInfo在where中斷了左連接。將它拉入連接。 – Paparazzi